C# how to change a COM port to an specified one

久未见 提交于 2019-12-11 07:56:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!