C#如何将COM端口更改为指定端口
我需要更改 USB 串行适配器的端口号,我有以下 rotine 来查找它,现在我需要将其 portName / COM Number 更改为 COM11 例如。
我正是需要这个,但是通过 C# 代码:
我的电脑 ->管理->设备管理器->端口->通讯端口->端口设置->高级-> COM 端口号
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
//If the serial port's instance name contains USB
//it must be a USB to serial device
if (queryObj["InstanceName"].ToString().Contains("USB"))
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
Console.WriteLine(queryObj["PortName"] + "is a USB to SERIAL adapter/converter");
string port = queryObj["PortName"].ToString();
SerialPort p = new SerialPort(port);
//p.PortName = "COM11";
return port ;
}
}
throw new Exception(Messages.PINPAD_NOT_FOUND);
}
I need to change the port number of a USB serial adapter, i have the following rotine to finding it, now I need to change its portName / COM Number to COM11 for example.
I need exactly this, but by C# code:
My Computer -> Manage -> Device Manager -> Ports -> Communications Port -> Port Settings -> Advanced -> COM Port Number
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
//If the serial port's instance name contains USB
//it must be a USB to serial device
if (queryObj["InstanceName"].ToString().Contains("USB"))
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
Console.WriteLine(queryObj["PortName"] + "is a USB to SERIAL adapter/converter");
string port = queryObj["PortName"].ToString();
SerialPort p = new SerialPort(port);
//p.PortName = "COM11";
return port ;
}
}
throw new Exception(Messages.PINPAD_NOT_FOUND);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 wmi 中不支持 com 端口重命名。从技术角度来看,您点的配置会更改附加到驱动程序的符号链接。我认为这是可行的,但你必须在DDK(也许在WDM)中查看它。
据我所知,您的程序的正确解决方案是能够适应硬件分配的任何名称。您应该将正确的端口名称存储在配置文件或注册表中的某个位置,并允许用户自定义它。
I don't think com port renaming is available in wmi. On technical point of view the configuration you point change the symbolinc link attached to a driver. I think it's doable but you have to look a it in DDK (Perhaps in the WDM).
As far as I know, the proper solution for your program, is to be able to adapt itself to whatever name the hardware was assigned. You should store the correct port name in a configuration file or in the registry somewhere and allow the user to customize it.