问题
I'm writing an application that communicates by sending bytes to the USB port. I'd like to allow the user to choose the port and to do that, I use SerialPort.GetPortNames()
. Unfortunately, it returns an empty array. The method supposedly reads the registry for data (HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM), but the SERIALCOMM directory is missing. When I run the program on Linux, it lists my four USB ports, as expected. How can I fix the registry/discover the ports in a different way?
回答1:
The SerialPort.GetPortNames()
are the correct method to discover serial ports. But if you are using Windows 7, I think it could be issues with permissions on the registry keys this method lists. I found a post which describe this problem at Microsoft.com.
回答2:
You could use Management Objects to query available COM ports. The interesting tables are:
- MSSerial_PortName in root\WMI
- MSWmi_PnPInstanceNames in root\WMI
- Win32_PnPEntity in root\CIMV2
You can explore these namespaces in the WMI Code Creator, and generate VBScript/VB/C# code.
回答3:
SerialPort.GetPortNames()
returns the list of COM ports install on the machine, not USB ports. I don't think Windows will provide you with a list of USB ports, only USB devices that are available.
Despite the name "Universal Serial Bus", they are not "Serial Ports" in the convential meaning.
来源:https://stackoverflow.com/questions/8624041/discover-serial-ports-in-c-sharp