在下面的方法中,我啓動了一個調用WMIC.exe的過程,以查詢連接的USB設備的DeviceID。 問題在於,有時雖然設備已插入,但WIMC不返回任何實例,就好像設備未插入一樣。然而,設備管理器同時顯示「端口(COM & LPT)」下的設備,這意味着WMIC的信息不準確。我的意思是,如果設備崩潰或以任何方式出現設備故障,並且需要某種重置,則它也不應該位於設備管理器列表中。WMIC.exe找不到插入的USB設備
的方法:
private string DonglePortName()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "C:\\Windows\\System32\\wbem\\WMIC.exe";
startInfo.Arguments = "PATH Win32_SerialPort GET /VALUE";
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
processTemp.Start();
string output = processTemp.StandardOutput.ReadToEnd();
int indexOfBGEntry = output.IndexOf("Bluegiga Bluetooth Low Energy");
if(indexOfBGEntry > -1)
{
string output_sub = output.Substring(indexOfBGEntry);
string str = "DeviceID=";
int i = output_sub.IndexOf(str);
int start = i + str.Length;
string substr = output_sub.Substring(start);
int end = substr.IndexOf("\r");
return output_sub.Substring(start, end);
}
return null;
}
在該點上的cmd窗口執行:
C:\\Windows\\System32\\wbem\\WMIC.exe PATH Win32_SerialPort GET /VALUE
回報:
No Instance(s) Available.
當同時設備管理器示出了設備(即使在單擊掃描硬件更改後)。
所以上面的C#代碼實際上並不需要證明這個問題,但我只有在這裏有人可以提出另一個更強大的方式來獲取設備端口(使用C#),或者可以指出原因因爲WMIC的不準確。
另一個線索是WMIC在讀取/寫入串行端口的代碼的另一部分的異常(和崩潰)後總是返回No Instance(s) Available
。然後我必須拔下並重新插入USB設備,然後再由WMIC「查看」。儘管如此,設備管理器在任何時候都會顯示設備。