问题
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);
}
回答1:
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.
来源:https://stackoverflow.com/questions/8805317/c-sharp-how-to-change-a-com-port-to-an-specified-one