请检查我正在使用的代码:
public static string AutoDetectArduinoPort()
{
ConnectionOptions options = PrepareOptions();
ManagementScope scope = PrepareScope(Environment.MachineName, options, @"\root\CIMV2");
// Prepare the query and searcher objects.
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
ManagementObjectSearcher portSearcher = new ManagementObjectSearcher(scope, objectQuery);
using (portSearcher)
{
string portName = "";
foreach (ManagementObject currentObject in portSearcher.Get())
{
if (currentObject != null)
{
object currentObjectCaption = currentObject["Caption"];
if (currentObjectCaption != null)
{
portName = currentObjectCaption.ToString();
if (portName.Contains("(COM"))
{
if (portName.Contains("Arduino")) // e.g. "Arduino Mega 2560 (COM3)"
{
portName = portName.Substring(portName.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
return portName;
}
}
}
}
}
}
return null;
}
我称之为:
string portName = AutoDetectArduinoPort();
MessageBox.Show(portName); // shows "COM3"
if (portName != null)
{
serialPort.PortName = portName;
serialPort.Open();
......
运行时异常(System.IO.IOException)抛出最后一行,说"端口' COM3'不存在。"它显示在设备管理器和所有。
我做错了什么?请帮我解决这个问题。具有讽刺意味的是,在Windows 10升级之前它运行良好:(