关于读取Com口数据时,Com口的名字的两种读法。

1,直接调用SerialPort类中的GetPortNames()方法.

      string[] portList = System.IO.Ports.SerialPort.GetPortNames();     

     // Com Port
     StringBuilder sb = new StringBuilder();

     if (portList.Length > 1)
    {
           for (int i = 0; i < portList.Length; ++i)
        {
              string strComPortName = portList[i];
              if (strComPortName.Equals("COM1"))
              {
                    i++;
              }
                 sb.Append(portList[i]);
                 sb.Append(" ");
          }
     }
        else
      {
         sb.Append("null");
       }

 2,调用Win32_SerialPort。(port["name"])

  

  var instances = new ManagementClass("Win32_SerialPort").GetInstances();
  foreach (ManagementObject port in instances)
  {
    // Console.WriteLine("{0}: {1}:{2}", port["deviceid"], port["name"], port["PowerManagementCapabilities"]);
  }

两种都差不多,不过个人感觉用第二种在系统运行的过程中,会慢一点,不知道有谁知道为神马?

原文地址:https://www.cnblogs.com/qianchunsheng/p/3584661.html