【问题标题】:Getting Serial Port Information获取串口信息
【发布时间】:2011-02-19 17:55:31
【问题描述】:

我有一些将串行端口加载到组合框中的代码:

     List<String> tList = new List<String>(); 

     comboBoxComPort.Items.Clear();

     foreach (string s in SerialPort.GetPortNames())
     {
        tList.Add(s);
     }

     tList.Sort();
     comboBoxComPort.Items.Add("Select COM port...");
     comboBoxComPort.Items.AddRange(tList.ToArray());
     comboBoxComPort.SelectedIndex = 0;

我想将端口描述(类似于设备管理器中显示的 COM 端口)添加到列表中并对列表中索引 0 之后的项目进行排序(已解决: 见上文 sn-p)。有人对添加端口描述有任何建议吗?我正在使用 Microsoft Visual C# 2008 Express Edition (.NET 2.0)。您可能有的任何想法将不胜感激。谢谢。

【问题讨论】:

标签: c# sorting combobox serial-port


【解决方案1】:

编辑:对不起,我太快回答你的问题了。我现在意识到您正在寻找一个包含端口名称 + 端口描述的列表。我已经相应地更新了代码......

使用 System.Management,您可以查询所有端口,以及每个端口的所有信息(就像设备管理器...)

示例代码(确保添加对 System.Management 的引用):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;        

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                var tList = (from n in portnames
                            join p in ports on n equals p["DeviceID"].ToString()
                            select n + " - " + p["Caption"]).ToList();

                tList.ForEach(Console.WriteLine);
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

更多信息在这里:http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx

【讨论】:

  • 当您可以只使用来自 ManagementObject 的 p["DeviceID"] 时,调用 SerialPort.GetPortNames(); 和 join 有什么意义?
  • 你保证只获取串口吗?如果没有,你怎么只收集串口?我很想知道...
  • 它没有显示已连接的 USB 转串口(它显示在设备管理器上)
  • 这个答案是错误的。为什么它有 44 票赞成???搜索 FROM WIN32_SerialPort 是错误的。此处的其他答案通过搜索 FROM Win32_PnPEntity 来正确完成。您的代码仅列出了我的 6 个 COM 端口中的 2 个!所有 USB 到 RS232 适配器的 COM 端口都完全丢失了!
【解决方案2】:

我在这里尝试了很多对我不起作用的解决方案,只显示了一些端口。但是下面显示了所有这些和他们的信息。

        using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
        {
            var portnames = SerialPort.GetPortNames();
            var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

            var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();

            foreach(string s in portList)
            {
                Console.WriteLine(s);
            }
        }
    }

【讨论】:

  • 这也是唯一对我有用的解决方案。其他解决方案没有列出我正在寻找的端口......这个有。
  • 你帮我节省时间
  • 此解决方案有效。如果您的 COM 端口高于 9,则将端口名与描述结合起来只有一个小问题。它连接例如COM16 与 COM1,因为它在 'COM16' 中找到字符串 'COM1'。我通过用 s.Contains('('+ n + ')') 更改 s.Contains(n) 来修复它
  • 这是这里唯一可行的解​​决方案。其他解决方案没有列出所有端口或空指针异常。
【解决方案3】:

使用下面的代码sn-p

执行时会给出如下输出。

serial port : Communications Port (COM1)
serial port : Communications Port (COM2)

别忘了添加

using System;
using System.Management;
using System.Windows.Forms;

同时添加对system.Management的引用(默认不可用)

C#

private void GetSerialPort()
{

    try
    {
        ManagementObjectSearcher searcher = 
            new ManagementObjectSearcher("root\\CIMV2", 
            "SELECT * FROM Win32_PnPEntity"); 

        foreach (ManagementObject queryObj in searcher.Get())
        {
            if (queryObj["Caption"].ToString().Contains("(COM"))
            {
                Console.WriteLine("serial port : {0}", queryObj["Caption"]);
            }

        }
    }
    catch (ManagementException e)
    {
        MessageBox.Show( e.Message);
    }

}

VB

  Private Sub GetAllSerialPortsName()
        Try
            Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_PnPEntity")
            For Each queryObj As ManagementObject In searcher.Get()
                If InStr(queryObj("Caption"), "(COM") > 0 Then
                    Console.WriteLine("serial port : {0}", queryObj("Caption"))
                End If
            Next
        Catch err As ManagementException
            MsgBox(err.Message)
        End Try
    End Sub

更新: 您也可以检查

if (queryObj["Caption"].ToString().StartsWith("serial port"))

而不是

if (queryObj["Caption"].ToString().Contains("(COM"))

【讨论】:

  • 我必须包含一个空检查,因为我的循环被评估了 82 次,有 3 个匹配项。其余的返回 null。 if ((queryObj["Caption"] != null) && (queryObj["Caption"].ToString().Contains("(COM")))
【解决方案4】:

有一个post about this same issue on MSDN:

在 C# 中获取有关串行端口的更多信息

嗨,Ravenb,

我们无法通过 SerialPort 类型获取信息。我不知道您为什么在应用程序中需要此信息。但是,有一个solved thread 和你有同样的问题。您可以查看那里的代码,看看它是否可以帮助您。

如果您还有任何问题,请随时告诉我。

最好的问候, 周小龙

那篇文章中的链接指向这个:

如何使用 System.IO.Ports.SerialPort 获取有关端口的更多信息

您可能可以从 WMI 查询中获取此信息。查看this tool 以帮助您找到正确的代码。你为什么会在意呢?这只是USB模拟器的一个细节,普通串口不会有这个。串口只知道“COMx”,仅此而已。

【讨论】:

  • 已解决线程的链接包含我所追求的代码。有点旧,但它可以从 PID&VID 获取 COM 端口号。谢谢+1
  • 那些引文中一些令人痛苦的缺乏经验的回应。有很多明显的理由需要这些信息。如果您要让用户选择要使用的端口,则要显示设备名称(不是 1995,因此仅提供 COM 端口列表是不行的),并且如果您正在使用特定的已知设备,您可以使用设备信息自动选择正确的端口。
【解决方案5】:

这里没有一个答案能满足我的需要。

Muno 的回答是错误,因为它只列出了 USB 端口。

code4life 的答案是错误,因为它列出了除 USB 端口之外的所有端口。 (尽管如此,它有 44 票赞成!!!)

我的电脑上有一个 EPSON 打印机模拟端口,这里的任何答案都没有列出。所以我不得不编写自己的解决方案。此外,我想显示更多信息,而不仅仅是标题字符串。我还需要将端口名称与描述分开。

我的代码已经在 Windows XP、Windows 7 和 Windows 10 上进行了测试。

必须从注册表中读取端口名称(如“COM1”),因为 WMI 不会为所有 COM 端口 (EPSON) 提供此信息。

如果你使用我的代码,你确实不再需要SerialPort.GetPortNames()。我的函数返回相同的端口,但有更多详细信息。为什么微软没有在框架中实现这样的功能??

using System.Management;
using Microsoft.Win32;

using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
    foreach (ManagementObject i_Inst in i_Entity.GetInstances())
    {
        Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
        if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
            continue; // Skip all devices except device class "PORTS"

        String s_Caption  = i_Inst.GetPropertyValue("Caption")     .ToString();
        String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
        String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
        String s_RegPath  = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
        String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();

        int s32_Pos = s_Caption.IndexOf(" (COM");
        if (s32_Pos > 0) // remove COM port from description
            s_Caption = s_Caption.Substring(0, s32_Pos);

        Console.WriteLine("Port Name:    " + s_PortName);
        Console.WriteLine("Description:  " + s_Caption);
        Console.WriteLine("Manufacturer: " + s_Manufact);
        Console.WriteLine("Device ID:    " + s_DeviceID);
        Console.WriteLine("-----------------------------------");
    }
}

我用很多 COM 端口测试了代码。这是控制台输出:

Port Name:    COM29
Description:  CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID:    USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name:    COM28
Description:  Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID:    USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name:    COM25
Description:  USB-SERIAL CH340
Manufacturer: wch.cn
Device ID:    USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name:    COM26
Description:  Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID:    USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name:    COM1
Description:  Comunications Port
Manufacturer: (Standard port types)
Device ID:    ACPI\PNP0501\1
-----------------------------------
Port Name:    COM999
Description:  EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0000
-----------------------------------
Port Name:    COM20
Description:  EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0001
-----------------------------------
Port Name:    COM8
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name:    COM9
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name:    COM30
Description:  Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID:    USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------

COM1是主板上的COM口。

COM 8 和 9 是蓝牙 COM 端口。

COM 25 和 26 是 USB 转 RS232 适配器。

COM 28、29 和 30 是类似 Arduino 的板。

COM 20 和 999 是 EPSON 端口。

【讨论】:

    【解决方案6】:

    我结合了以前的答案并使用了 Win32_PnPEntity 类的结构,可以在here 找到。 得到这样的解决方案:

    using System.Management;
    public static void Main()
    {
         GetPortInformation();
    }
    
    public string GetPortInformation()
        {
            ManagementClass processClass = new ManagementClass("Win32_PnPEntity");
            ManagementObjectCollection Ports = processClass.GetInstances();           
            foreach (ManagementObject property in Ports)
            {
                var name = property.GetPropertyValue("Name");               
                if (name != null && name.ToString().Contains("USB") && name.ToString().Contains("COM"))
                {
                    var portInfo = new SerialPortInfo(property);
                    //Thats all information i got from port.
                    //Do whatever you want with this information
                }
            }
            return string.Empty;
        }
    

    SerialPortInfo 类:

    public class SerialPortInfo
    {
        public SerialPortInfo(ManagementObject property)
        {
            this.Availability = property.GetPropertyValue("Availability") as int? ?? 0;
            this.Caption = property.GetPropertyValue("Caption") as string ?? string.Empty;
            this.ClassGuid = property.GetPropertyValue("ClassGuid") as string ?? string.Empty;
            this.CompatibleID = property.GetPropertyValue("CompatibleID") as string[] ?? new string[] {};
            this.ConfigManagerErrorCode = property.GetPropertyValue("ConfigManagerErrorCode") as int? ?? 0;
            this.ConfigManagerUserConfig = property.GetPropertyValue("ConfigManagerUserConfig") as bool? ?? false;
            this.CreationClassName = property.GetPropertyValue("CreationClassName") as string ?? string.Empty;
            this.Description = property.GetPropertyValue("Description") as string ?? string.Empty;
            this.DeviceID = property.GetPropertyValue("DeviceID") as string ?? string.Empty;
            this.ErrorCleared = property.GetPropertyValue("ErrorCleared") as bool? ?? false;
            this.ErrorDescription = property.GetPropertyValue("ErrorDescription") as string ?? string.Empty;
            this.HardwareID = property.GetPropertyValue("HardwareID") as string[] ?? new string[] { };
            this.InstallDate = property.GetPropertyValue("InstallDate") as DateTime? ?? DateTime.MinValue;
            this.LastErrorCode = property.GetPropertyValue("LastErrorCode") as int? ?? 0;
            this.Manufacturer = property.GetPropertyValue("Manufacturer") as string ?? string.Empty;
            this.Name = property.GetPropertyValue("Name") as string ?? string.Empty;
            this.PNPClass = property.GetPropertyValue("PNPClass") as string ?? string.Empty;
            this.PNPDeviceID = property.GetPropertyValue("PNPDeviceID") as string ?? string.Empty;
            this.PowerManagementCapabilities = property.GetPropertyValue("PowerManagementCapabilities") as int[] ?? new int[] { };
            this.PowerManagementSupported = property.GetPropertyValue("PowerManagementSupported") as bool? ?? false;
            this.Present = property.GetPropertyValue("Present") as bool? ?? false;
            this.Service = property.GetPropertyValue("Service") as string ?? string.Empty;
            this.Status = property.GetPropertyValue("Status") as string ?? string.Empty;
            this.StatusInfo = property.GetPropertyValue("StatusInfo") as int? ?? 0;
            this.SystemCreationClassName = property.GetPropertyValue("SystemCreationClassName") as string ?? string.Empty;
            this.SystemName = property.GetPropertyValue("SystemName") as string ?? string.Empty;
        }
    
        int Availability;
        string Caption;
        string ClassGuid;
        string[] CompatibleID;
        int ConfigManagerErrorCode;
        bool ConfigManagerUserConfig;
        string CreationClassName;
        string Description;
        string DeviceID;
        bool ErrorCleared;
        string ErrorDescription;
        string[] HardwareID;
        DateTime InstallDate;
        int LastErrorCode;
        string Manufacturer;
        string Name;
        string PNPClass;
        string PNPDeviceID;
        int[] PowerManagementCapabilities;
        bool PowerManagementSupported;
        bool Present;
        string Service;
        string Status;
        int StatusInfo;
        string SystemCreationClassName;
        string SystemName;       
    
    }
    

    【讨论】:

    • 可能是此页面上的最佳解决方案。除了能够按其他字段进行过滤外,您还可以获得您可能需要的所有其他设备信息。
    • 如果连接了许多com端口设备,我们如何知道谁是谁?我看到很多设备根本没有hardwareid!!!所以没有办法自动识别它,我们总是必须手动选择COM端口!!!! (((
    • 这绝对是页面上最好的答案,我唯一的补充是添加一个 COMPort 属性并从标题中提取实际的 com 端口值(例如 COM15),以使其更易于使用。但是一个卓越的解决方案。
    • 这个答案是错误的。为什么只列出USB端口?您的代码省略了我主板上的 COM 端口。该问题并未专门针对 USB COM 端口。删除:&& name.ToString().Contains("USB")
    【解决方案7】:

    我不太清楚您所说的“对索引 0 后的项目进行排序”是什么意思,但如果您只想对 SerialPort.GetPortNames() 返回的字符串数组进行排序,您可以使用 Array.Sort。

    【讨论】:

    • 我已在原始问题中添加了详细信息。谢谢。
    【解决方案8】:
    this.comboPortName.Items.AddRange(
        (from qP in System.IO.Ports.SerialPort.GetPortNames()
         orderby System.Text.RegularExpressions.Regex.Replace(qP, "~\\d",
         string.Empty).PadLeft(6, '0')
         select qP).ToArray()
    );
    

    【讨论】:

    • 不要只发布一段代码,请解释为什么这段代码可以解决所提出的问题。没有解释,这不是答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多