Advertisement
saper_2

C# CLass for getting list of SerialPorts with Friendly names

Jan 8th, 2014
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.54 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Management;
  5. using System.IO.Ports;
  6. // Add System.Management to References
  7.  
  8. /* E.g.:
  9. SerialPortLister spl = new SerialPortLister(false);
  10. string[] portlist = spl.GetSerialPorts();
  11. MessageBox.Show(string.Join(Environment.NewLine, portlist), "Detailed serial port list", MessageBoxButtons.OK, MessageBoxIcon.Information);
  12. */
  13.  
  14. public class SerialPortListerItem
  15. {
  16.     private string pName = "";
  17.     private string pDesc = "";
  18.     private bool isModem = false;
  19.     private ManagementScope manScope = null;
  20.     private bool fastScanMode = false;
  21.  
  22.     public string PortName { get { return pName; } }
  23.     public string Description { get { return pDesc; } }
  24.     public bool IsModem { get { return isModem; } }
  25.     /// <summary>
  26.     /// If true, then getting name and description is faster but IsModem property is not updated.
  27.     /// </summary>
  28.     public bool FastMode { set { fastScanMode = FastMode; } get { return fastScanMode; } }
  29.  
  30.     /// <summary>
  31.     /// Update port information (description, IsModem - when FastMode is false).
  32.     /// </summary>
  33.     public void UpdatePortInfo()
  34.     {
  35.         int noRes = 0;
  36.        
  37.         // two scan modes
  38.         if (fastScanMode)
  39.         {
  40.             try
  41.             {
  42.                 ManagementObjectSearcher searcher;
  43.  
  44.                 if (manScope != null)
  45.                 {
  46.                     ObjectQuery manQuery = new ObjectQuery("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
  47.                     searcher = new ManagementObjectSearcher(manScope, manQuery);
  48.                 }
  49.                 else
  50.                 {
  51.                     searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
  52.                 }
  53.  
  54.                 if (searcher.Get().Count > 0)
  55.                 {
  56.                     foreach (ManagementObject queryObj in searcher.Get())
  57.                     {
  58.                         if (queryObj["Caption"] != null)
  59.                         {
  60.                             string cap = (string)queryObj["Caption"];
  61.                             if (cap.Contains("(COM"))
  62.                             { // yep it's a com port
  63.                                 string name = cap.Substring(cap.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
  64.                                 if (name.ToUpper() == pName.ToUpper())
  65.                                 {
  66.                                     pDesc = cap.Substring(0, cap.LastIndexOf("(") - 1);
  67.                                 }
  68.                             }
  69.                         }
  70.                     }
  71.                 }
  72.             }
  73.             catch
  74.             {
  75.  
  76.             }
  77.         }
  78.             // FastMode = false, slower scan but can tell witch port is a Modem
  79.         else
  80.         {
  81.  
  82.             // check com port as normal serial port
  83.             try
  84.             {
  85.                 ManagementObjectSearcher searcher;
  86.  
  87.                 if (manScope != null)
  88.                 {
  89.                     ObjectQuery manQuery = new ObjectQuery("root\\CIMV2", "SELECT * FROM Win32_SerialPort WHERE DeviceID=\"" + pName.ToUpper() + "\"");
  90.                     searcher = new ManagementObjectSearcher(manScope, manQuery);
  91.                 }
  92.                 else
  93.                 {
  94.                     searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort WHERE DeviceID=\"" + pName.ToUpper() + "\"");
  95.                 }
  96.  
  97.                 //noRes = 0;
  98.                 if (searcher.Get().Count > 0)
  99.                 {
  100.                     foreach (ManagementObject queryObj in searcher.Get())
  101.                     {
  102.                         if (((string)queryObj["DeviceID"]).ToUpper() == pName.ToUpper())
  103.                         {
  104.                             //pDesc = (string)queryObj["Caption"];
  105.                             pDesc = (string)queryObj["Description"];
  106.                             isModem = false;
  107.                         }
  108.                     }
  109.                 }
  110.                 else
  111.                 {
  112.                     noRes = 1;
  113.                 }
  114.  
  115.             }
  116.             catch //(ManagementException e)
  117.             {
  118.             }
  119.             // re-check port as modem port
  120.             try
  121.             {
  122.                 ManagementObjectSearcher searcher;
  123.  
  124.                 if (manScope != null)
  125.                 {
  126.                     ObjectQuery manQuery = new ObjectQuery("root\\CIMV2", "SELECT * FROM Win32_POTSModem WHERE AttachedTo=\"" + pName.ToUpper() + "\"");
  127.                     searcher = new ManagementObjectSearcher(manScope, manQuery);
  128.                 }
  129.                 else
  130.                 {
  131.                     searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_POTSModem WHERE AttachedTo=\"" + pName.ToUpper() + "\"");
  132.                 }
  133.  
  134.  
  135.                 //noRes = 0;
  136.                 if (searcher.Get().Count > 0)
  137.                 {
  138.                     foreach (ManagementObject queryObj in searcher.Get())
  139.                     {
  140.                         if (((string)queryObj["AttachedTo"]).ToUpper() == pName.ToUpper())
  141.                         {
  142.                             pDesc = (string)queryObj["Caption"];
  143.                             isModem = true;
  144.                         }
  145.                     }
  146.                 }
  147.                 else
  148.                 {
  149.                     noRes = 1;
  150.                 }
  151.  
  152.                 // search it in Win32_PNPEntity class
  153.             }
  154.             catch
  155.             {
  156.             }
  157.  
  158.             try
  159.             {
  160.                 if (noRes == 1)
  161.                 {
  162.                     ManagementObjectSearcher searcher;
  163.  
  164.                     if (manScope != null)
  165.                     {
  166.                         ObjectQuery manQuery = new ObjectQuery("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
  167.                         searcher = new ManagementObjectSearcher(manScope, manQuery);
  168.                     }
  169.                     else
  170.                     {
  171.                         searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
  172.                     }
  173.  
  174.                     if (searcher.Get().Count > 0)
  175.                     {
  176.                         foreach (ManagementObject queryObj in searcher.Get())
  177.                         {
  178.                             if (queryObj["Caption"] != null)
  179.                             {
  180.                                 string cap = (string)queryObj["Caption"];
  181.                                 if (cap.Contains("(COM"))
  182.                                 { // yep it's a com port
  183.                                     string name = cap.Substring(cap.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);
  184.                                     if (name.ToUpper() == pName.ToUpper())
  185.                                     {
  186.                                         pDesc = cap.Substring(0, cap.LastIndexOf("(") - 1);
  187.                                     }
  188.                                 }
  189.                             }
  190.                         }
  191.                     }
  192.                 }
  193.             }
  194.             catch
  195.             {
  196.  
  197.             }
  198.         }
  199.     }
  200.  
  201.     /// <summary>
  202.     /// init class and fill up data
  203.     /// </summary>
  204.     /// <param name="portName">Serial port name</param>
  205.     /// <param name="fastMode">Decide if data should be obtained faster or slower</param>
  206.     public SerialPortListerItem(string portName, bool fastMode = false)
  207.     {
  208.         pName = portName;
  209.         fastScanMode = fastMode;
  210.         UpdatePortInfo();
  211.         manScope = null;
  212.  
  213.     }
  214.  
  215.     /// <summary>
  216.     /// init class and fill up data
  217.     /// </summary>
  218.     /// <param name="portName">Serial port name</param>
  219.     /// <param name="scope"></param>
  220.     /// <param name="fastMode">Decide if data should be obtained faster or slower</param>
  221.     public SerialPortListerItem(string portName, ManagementScope scope, bool fastMode = false)
  222.     {
  223.         pName = portName;
  224.         fastScanMode = fastMode;
  225.         UpdatePortInfo();
  226.         manScope = scope;
  227.     }
  228.  
  229. }
  230.  
  231. public class SerialPortLister
  232. {
  233.     // Com port list
  234.     private List<string> serPortList = new List<string>();
  235.     private List<SerialPortListerItem> spList = new List<SerialPortListerItem>();
  236.     private bool fastScanMode = false;
  237.     private ManagementScope connectionScope;
  238.  
  239.  
  240.     public int Count { get { return spList.Count; } }
  241.     public SerialPortListerItem this[int index] { get { return spList[index]; } }
  242.     public SerialPortListerItem this[string portName] {
  243.         get {
  244.             //return spList[index];
  245.             int idx = -1;
  246.             for (int i = 0; i < spList.Count; i++)
  247.             {
  248.                 if (portName.ToUpper() == spList[i].PortName.ToUpper())
  249.                 {
  250.                     idx = i;
  251.                 }
  252.             }
  253.             if (idx > -1) return spList[idx];
  254.            
  255.             return null;
  256.         }
  257.     }
  258.  
  259.     private void FillPortList()
  260.     {
  261.         string[] pl = SerialPort.GetPortNames();
  262.         if (pl.Length < 1) return;
  263.  
  264.         serPortList.Clear();
  265.         foreach (string s in pl)
  266.         {
  267.             serPortList.Add(s);
  268.         }
  269.     }
  270.  
  271.     /// <summary>
  272.     /// Build final port list for class
  273.     /// </summary>
  274.     private void BuildPortList()
  275.     {
  276.         if (serPortList.Count < 1) return;
  277.         spList.Clear();
  278.         foreach (string s in serPortList)
  279.         {
  280.             SerialPortListerItem i = new SerialPortListerItem(s, connectionScope, fastScanMode);
  281.             spList.Add(i);
  282.         }
  283.     }
  284.  
  285.     /// <summary>
  286.     /// Constructor
  287.     /// </summary>
  288.     public SerialPortLister(bool FastScanMode=false)
  289.     {
  290.         connectionScope = new ManagementScope(@"\\" + Environment.MachineName);
  291.         fastScanMode = FastScanMode;
  292.         FillPortList();
  293.         BuildPortList();
  294.     }
  295.  
  296.     /// <summary>
  297.     /// Returns array of port names in format "[PortName] - [Description]"
  298.     /// </summary>
  299.     /// <returns>Array of port names with description</returns>
  300.     public string[] GetSerialPorts()
  301.     {
  302.         string[] s = new string[spList.Count];
  303.  
  304.         for (int i = 0; i < spList.Count; i++)
  305.         {
  306.             string ss = spList[i].PortName.ToUpper() + " - " + spList[i].Description;
  307.             s[i] = ss;
  308.         }
  309.         return s;
  310.     }
  311.  
  312.     /// <summary>
  313.     /// Get serial port description (port device name) by port name
  314.     /// </summary>
  315.     /// <param name="portName">Port name, eg.: COM2, com3, etc...</param>
  316.     /// <returns>Port device name</returns>
  317.     public string GetSerialPortDesc(string portName)
  318.     {
  319.         SerialPortListerItem sp = this[portName];
  320.         if (sp != null) return sp.Description;
  321.  
  322.         return "";
  323.     }
  324.  
  325.     /// <summary>
  326.     /// Returns serial port name from string formatted in format: "[portName] - [description]"
  327.     /// </summary>
  328.     /// <param name="SerialPortNameWithDescription">Port name with description separated by text " - "</param>
  329.     /// <returns>port name (upper case)</returns>
  330.     public string DecodeSerialPortName(string SerialPortNameWithDescription)
  331.     {
  332.         string s = SerialPortNameWithDescription; // this parameter is too long :)
  333.  
  334.         if (s.IndexOf(' ') > 3)
  335.         {
  336.             s = s.Substring(0, s.IndexOf(' '));
  337.         }
  338.  
  339.         return s.Trim().ToUpper();
  340.  
  341.     }
  342.    
  343. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement