简体   繁体   English

在C#中发现串行端口

[英]Discover serial ports in C#

I'm writing an application that communicates by sending bytes to the USB port. 我正在编写一个通过将字节发送到USB端口进行通信的应用程序。 I'd like to allow the user to choose the port and to do that, I use SerialPort.GetPortNames() . 我想允许用户选择端口并执行此操作,我使用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. 该方法应该读取注册表以获取数据(HKEY_LOCAL_MACHINE \\ HARDWARE \\ DEVICEMAP \\ SERIALCOMM),但是缺少SERIALCOMM目录。 When I run the program on Linux, it lists my four USB ports, as expected. 当我在Linux上运行该程序时,它会按预期列出我的四个USB端口。 How can I fix the registry/discover the ports in a different way? 如何修复注册表/以其他方式发现端口?

You could use Management Objects to query available COM ports. 您可以使用管理对象来查询可用的COM端口。 The interesting tables are: 有趣的表是:

You can explore these namespaces in the WMI Code Creator , and generate VBScript/VB/C# code. 您可以在WMI Code Creator中浏览这些命名空间,并生成VBScript / VB / C#代码。

The SerialPort.GetPortNames() are the correct method to discover serial ports. SerialPort.GetPortNames()是发现串行端口的正确方法。 But if you are using Windows 7, I think it could be issues with permissions on the registry keys this method lists. 但是,如果您使用的是Windows 7,我认为此方法列出的注册表项权限可能存在问题。 I found a post which describe this problem at Microsoft.com . 我在Microsoft.com上找到了描述此问题的帖子。

SerialPort.GetPortNames() returns the list of COM ports install on the machine, not USB ports. SerialPort.GetPortNames()返回计算机上安装的COM端口列表,而不是USB端口列表。 I don't think Windows will provide you with a list of USB ports, only USB devices that are available. 我认为Windows不会为您提供USB端口列表,而只是提供可用的USB设备。

Despite the name "Universal Serial Bus", they are not "Serial Ports" in the convential meaning. 尽管名称为“通用串行总线”,但在常规意义上它们不是“串行端口”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM