简体   繁体   中英

How to get only User interface Com port from list of ports?

I am developing a C#.net app in which I have communication with a USB 3G modems Com port for sending and receiving messages.

Below is my code that I am currently using for getting a list of ports:

string[] ports = SerialPort.GetPortNames();

Now I want to get only UI port from list of port, for example if 3G modem has two ports say for COM4 and COM6 in which first is Application interface port and another is UI port.

How can I programmatically get the UI port?

A serial port doesn't know what is connected on the other side. You need to try to open each one and send something like "AT\\r\\n" and expect "OK" to check on which one your modem is connected.

EDIT:

    using System;
    using System.IO.Ports;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;


    private static bool IsModem(string PortName)
    {

      SerialPort port= null;
       try
       { 
         port = new SerialPort(PortName,9600); //9600 baud is supported by most modems
         port.ReadTimeout = 200;
         port.Open();
         port.Write("AT\r\n");

         //some modems will return "OK\r\n"
         //some modems will return "\r\nOK\r\n"
         //some will echo the AT first
         //so
         for(int i=0;i<4;i++) //read a maximum of 4 lines in case some other device is posting garbage
         {
              string line = port.ReadLine();
              if(line.IndexOf("OK")!=-1)
              {
                 return true;
              }
         }
        return false;


       }
       catch(Exception ex)
       {
         // You should implement more specific catch blocks so that you would know 
         // what the problem was, ie port may be in use when you are trying
         // to test it so you should let the user know that as he can correct that fault

          return false;
       }
       finally
       {
         if(port!=null)
         {
            port.Close();
         }     
       }



    }

    public static string[] FindModems()
    {
      List<string> modems = new List<string>();
      string[] ports = SerialPort.GetPortNames();

       for(int i =0;i<ports.Length;i++)
       {
         if(IsModem(ports[i]))
         {
           modems.Add(ports[i]);
         }
        }
        return modems.ToArray();
    }

Something like this should work, I didn't test it ( can't test it ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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