標籤:
最近用C#寫安裝usb驅動,必須得調用API SetupCopyOEMInf:
BOOL WINAPI SetupCopyOEMInf( _In_ PCTSTR SourceInfFileName, _In_ PCTSTR OEMSourceMediaLocation, _In_ DWORD OEMSourceMediaType, _In_ DWORD CopyStyle, _Out_opt_ PTSTR DestinationInfFileName, _In_ DWORD DestinationInfFileNameSize, _Out_opt_ PDWORD RequiredSize, _Out_opt_ PTSTR DestinationInfFileNameComponent);
於是在C#裡這麼寫了:
[DllImport("setupapi.dll", SetLastError = true)] private static extern bool SetupCopyOEMInf( string SourceInfFileName, string OEMSourceMediaLocation, OemSourceMediaType OEMSourceMediaType, OemCopyStyle CopyStyle, out string DestinationInfFileName, int DestinationInfFileNameSize, int RequiredSize, out string DestinationInfFileNameComponent );
其中DestinationInfFileName代表驅動成功安裝後,inf檔案在C:\Windows\inf目錄下的絕對路徑,這個inf檔案名稱字和原inf檔案不一樣,但是內容是一模一樣的,不知道為啥inf驅動安裝成功後會把inf檔案換一個名字然後copy到C:\Windows\inf目錄下?有高人解答下嗎?
DestinationInfFileNameComponent代表copy到C:\Windows\inf目錄下的那個inf的名字,這個很有用,調用SetupUninstallOEMInf卸載驅動的時候要用到這個名字。
然後我在C#中這麼調用SetupCopyOEMInf:
unsafe { success = SetupCopyOEMInf(infPath, "", OemSourceMediaType.SPOST_PATH, OemCopyStyle.SP_COPY_NEWER, out destinationInfFileName, 260, 0, out destinationInfFileNameComponent); }
260是檔案目錄的最大長度,查看log,C:\Windows\inf\setupapi.dev.log,可以成功安裝,success為true,但是接下來的問題困擾了我好久,destinationInfFileNameComponent和destinationInfFileName始終都沒有值,按照https://msdn.microsoft.com/en-us/library/aa376990.aspx上的說話,成功執行後會返回這倆值,destinationInfFileNameComponent是調用SetupUninstallOEMInf卸載驅動的必傳參數,沒有值就無法卸載了,google了半天沒有解決,最後看別人用C++寫的SetupCopyOEMInf,destinationInfFileName傳的是一個長度為260的TCHAR數組,於是我把C#的SetupCopyOEMInf原型改為:
[DllImport("setupapi.dll", SetLastError = true)] private static extern bool SetupCopyOEMInf( string SourceInfFileName, string OEMSourceMediaLocation, OemSourceMediaType OEMSourceMediaType, OemCopyStyle CopyStyle, out char[] DestinationInfFileName, int DestinationInfFileNameSize, int RequiredSize, out string DestinationInfFileNameComponent );
然後把destinationInfFileName聲明為一個260長度的char數組,但是調用會報executionexception的異常。後來把原型參數char[] destinationInfFileName前面的out去掉,destinationInfFileNameComponent的值終於正確得到了!!!!!!!!
但是destinationInfFileName依然無法得到,好歹有了一個,終於可以做卸載了,具體為什麼可以了也不太清楚,為什麼PTSTR DestinationInfFileName傳遞C#的string不對?傳遞char數組才可以,但是無法使用out,估計destinationInfFileNameComponent是在destinationInfFileName的基礎上得到的,所以傳遞string類型的destinationInfFileNameComponent是可以的吧,糊塗了!
請問大神,在C#裡如何調用SetupCopyOEMInf可以正確獲得destinationInfFileNameComponent和destinationInfFileName這倆值!
參考:
http://www.pinvoke.net/default.aspx/setupapi.SetupCopyOEMInf
https://msdn.microsoft.com/en-us/library/aa376990.aspx
http://stackoverflow.com/questions/18404660/how-to-use-setupcopyoeminf-during-installer
C# SetupCopyOEMInf安裝驅動並返回DestinationInfFileNameComponent