获取串口信息

Jim*_*ell 31 c# sorting combobox serial-port

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

     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;
Run Code Online (Sandbox Code Playgroud)

我想将端口描述(类似于设备管理器中的COM端口所示)添加到列表中,并对列表中位于索引0之后的项进行排序(已解决:请参阅上面的代码段).有没有人有任何关于添加端口描述的建议?我使用的是Microsoft Visual C#2008 Express Edition(.NET 2.0).您可能有任何想法,将不胜感激.谢谢.

cod*_*ife 42

编辑: 对不起,我把你的问题拉得过快了.我现在意识到你正在寻找一个包含端口名称+端口描述的列表.我相应地更新了代码......

使用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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这个答案是错误的。为什么有 44 票赞成???搜索 FROM WIN32_SerialPort 是错误的。这里的其他答案通过搜索 FROM Win32_PnPEntity 正确地做到了这一点。你的代码只列出了我的 6 个 COM 端口中的 2 个!所有 USB 转 RS232 适配器 COM 端口完全丢失! (4认同)
  • 它没有显示已连接的 USB 到串行转换(它显示在设备管理器上) (3认同)

Sac*_*van 30

使用以下代码段

它在执行时给出以下输出.

serial port : Communications Port (COM1)
serial port : Communications Port (COM2)
Run Code Online (Sandbox Code Playgroud)

别忘了添加

using System;
using System.Management;
using System.Windows.Forms;
Run Code Online (Sandbox Code Playgroud)

还添加引用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);
    }

}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

更新:您也可以检查

if (queryObj["Caption"].ToString().StartsWith("serial port"))
Run Code Online (Sandbox Code Playgroud)

代替

if (queryObj["Caption"].ToString().Contains("(COM"))
Run Code Online (Sandbox Code Playgroud)

  • 我必须包括一个空检查,因为我的循环被评估了82次,有3次匹配.其余的返回null.if((queryObj ["Caption"]!= null)&&(queryObj ["Caption"].ToString().Contains("(COM"))) (4认同)

小智 17

我在这里尝试了很多解决方案,这对我来说不起作用,只显示了一些端口.但以下显示了所有这些及其信息.

        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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案有效。如果您的 COM 端口高于 9,则将端口名称与描述结合起来只会出现一个小问题。例如,它将 COM16 与 COM1 连接,因为它在“COM16”中找到字符串“COM1”。我通过将 s.Contains(n) 更改为 s.Contains('('+ n + ')') 来修复它 (6认同)
  • 你帮我节省了几个小时 (2认同)

Bra*_*ord 16

在MSDN上有一篇关于同样问题帖子:

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

嗨Ravenb,

我们无法通过SerialPort类型获取信息.我不知道为什么你的应用程序需要这些信息.但是,有一个解决的线程与您有相同的问题.您可以查看那里的代码,看看它是否可以帮助您.

如果您有任何其他问题,请随时告诉我.

最诚挚的问候,周小姐

该帖子中的链接转到了这个链接:

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

您可以从WMI查询中获取此信息.查看此工具可帮助您找到正确的代码.你为什么要关心?这只是USB仿真器的一个细节,普通的串口不会有这个.串口简单地通过"COMx"知道,仅此而已.

  • 这些报价中有些痛苦的经验不足.想要这些信息有很多明显的理由.如果您有一个用户选择要使用的端口,您想要显示设备名称(它不是1995,所以只提供COM端口列表是不行的),如果您正在使用特定的已知设备,您可以使用设备信息自动选择正确的端口. (23认同)

Mun*_*uno 9

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

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;
    }
Run Code Online (Sandbox Code Playgroud)

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;       

}
Run Code Online (Sandbox Code Playgroud)


Elm*_*mue 8

这里的答案都不能满足我的需求。

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("-----------------------------------");
    }
}
Run Code Online (Sandbox Code Playgroud)

我用很多 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
-----------------------------------
Run Code Online (Sandbox Code Playgroud)

COM1 是主板上的 COM 端口。

COM 8 和 9 是蓝牙 COM 端口。

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

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

COM 20 和 999 是 EPSON 端口。