C#是否提供了扫描可用COM端口的有效方法?我想在我的应用程序中有一个下拉列表,其中用户可以选择一个检测到的COM端口。创建和填充下拉列表不是问题。我只需要知道如何使用C#扫描可用的COM端口。我使用的是Microsoft Visual C#2008 Express Edition。感谢。
答案 0 :(得分:15)
System.IO.Ports是您想要的命名空间。
SerialPort.GetPortNames将列出所有串行COM端口。
不幸的是,并不直接从C#支持并行端口,因为除了传统情况之外,它们很少使用。也就是说,您可以通过查询以下注册表项来列出它们:
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\PARALLEL PORTS
有关详细信息,请参阅Microsoft.Win32命名空间。
答案 1 :(得分:2)
通过System.Management命名空间使用WMI。一个快速的谷歌找到这个代码:
using System;
using System.Management;
public class Foo
{
public static void Main()
{
var instances = new ManagementClass("Win32_SerialPort").GetInstances();
foreach ( ManagementObject port in instances )
{
Console.WriteLine("{0}: {1}", port["deviceid"], port["name"]);
}
}
答案 2 :(得分:1)
经过几次尝试后,我写了这样的东西:
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Text.RegularExpressions;
namespace Julo.SerialComm
{
public static class SerialPorts
{
public static List<SerialPortInfo> GetSerialPortsInfo()
{
var retList = new List<SerialPortInfo>();
// System.IO.Ports.SerialPort.GetPortNames() returns port names from Windows Registry
var registryPortNames = SerialPort.GetPortNames().ToList();
var managementObjectSearcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity");
var managementObjectCollection = managementObjectSearcher.Get();
foreach (var n in registryPortNames)
{
Console.WriteLine($"Searching for {n}");
foreach (var p in managementObjectCollection)
{
if (p["Caption"] != null)
{
string caption = p["Caption"].ToString();
string pnpdevid = p["PnPDeviceId"].ToString();
if (caption.Contains("(" + n + ")"))
{
Console.WriteLine("PnPEntity port found: " + caption);
var props = p.Properties.Cast<PropertyData>().ToArray();
retList.Add(new SerialPortInfo(n, caption, pnpdevid));
break;
}
}
}
}
retList.Sort();
return retList;
}
public class SerialPortInfo : IComparable
{
public SerialPortInfo() {}
public SerialPortInfo(string name, string caption, string pnpdeviceid)
{
Name = name;
Caption = caption;
PNPDeviceID = pnpdeviceid;
// build shorter version of PNPDeviceID for better reading
// from this: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\7&11A88E8E&0&000000000000_0000000C
// to this: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000
try
{
// split by "\" and take 2 elements
PNPDeviceIDShort = string.Join($"\\", pnpdeviceid.Split('\\').Take(2));
}
// todo: check if it can be split instead of using Exception
catch (Exception)
{
// or just take 32 characters if split by "\" is impossible
PNPDeviceIDShort = pnpdeviceid.Substring(0, 32) + "...";
}
}
/// <summary>
/// COM port name, "COM3" for example
/// </summary>
public string Name { get; }
/// <summary>
/// COM port caption from device manager
/// "Intel(R) Active Management Technology - SOL (COM3)" for example
/// </summary>
public string Caption { get; }
/// <summary>
/// PNPDeviceID from device manager
/// "PCI\VEN_8086&DEV_A13D&SUBSYS_224D17AA&REV_31\3&11583659&0&B3" for example
/// </summary>
public string PNPDeviceID { get; }
/// <summary>
/// Shorter version of PNPDeviceID
/// "PCI\VEN_8086&DEV_A13D&SUBSYS_224D17AA&REV_31" for example
/// </summary>
public string PNPDeviceIDShort { get; }
/// <summary>
/// Comparer required to sort by COM port properly (number as number, not string (COM3 before COM21))
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int CompareTo(object obj)
{
try
{
int a, b;
string sa, sb;
sa = Regex.Replace(Name, "[^0-9.]", "");
sb = Regex.Replace(((SerialPortInfo)obj).Name, "[^0-9.]", "");
if (!int.TryParse(sa, out a))
throw new ArgumentException(nameof(SerialPortInfo) + ": Cannot convert {0} to int32", sa);
if (!int.TryParse(sb, out b))
throw new ArgumentException(nameof(SerialPortInfo) + ": Cannot convert {0} to int32", sb);
return a.CompareTo(b);
}
catch (Exception)
{
return 0;
}
}
public override string ToString()
{
return string.Join(Environment.NewLine, Name, Caption, PNPDeviceID);
}
}
}
}
我用它来显示详细的串口列表,如下所示: