C# 使用Microsoft.Management.Infrastructure检索串行端口信息

C# 使用Microsoft.Management.Infrastructure检索串行端口信息,c#,.net-core,serial-port,system.management,C#,.net Core,Serial Port,System.management,为了获得有关串行端口设备的信息,使用System.Management,我们可以执行以下操作: 使用系统; 使用制度管理; 使用System.Collections.Generic; 使用System.Linq; 使用System.IO.Ports; 命名空间控制台应用程序1 { 班级计划 { 静态void Main(字符串[]参数) { 使用(var searcher=newmanagementobjectsearcher) (“从WIN32_SerialPort中选择*)) { string

为了获得有关串行端口设备的信息,使用
System.Management
,我们可以执行以下操作:

使用系统;
使用制度管理;
使用System.Collections.Generic;
使用System.Linq;
使用System.IO.Ports;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
使用(var searcher=newmanagementobjectsearcher)
(“从WIN32_SerialPort中选择*))
{
string[]portnames=SerialPort.GetPortNames();
var ports=searcher.Get().Cast().ToList();
var tList=(从端口名中的n开始)
在n等于p[“DeviceID”]的端口中加入p。ToString()
选择n+“-”+p[“Caption”]).ToList();
tList.ForEach(Console.WriteLine);
}
//暂停程序执行以查看结果。。。
控制台写入线(“按回车键退出”);
Console.ReadLine();
}
}
}
如何使用Microsoft.Management.Infrastructure实现这一点,我还没有找到示例,文档也不够详细。

非常类似:

  • 创建一个,其中指定计算机名(
    null
    用于LocalHost)和一个对象(需要传递用于身份验证的常用用户名和密码)。这反映了System.Management的
    连接选项
  • 使用CimSession的方法构建查询,传递名称空间和类。这反映了系统、管理层和
  • QueryInstances()
    返回一个对象(好消息是这里没有返回COM对象)
  • 得到你所关心的一切
请注意,您在WMI查询中跳过了and,这在性能上不是很好

然后可以将您的查询转换为:

using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;

using (var session = CimSession.Create(null) { 
    var ports = session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM WIN32_SerialPort");
    string[] portnames = SerialPort.GetPortNames();

    var tList = (from n in portnames
                join p in ports on n equals p.CimInstanceProperties["DeviceID"].Value
                select n + " - " + p.CimInstanceProperties["Caption"].Value);
}
我不知道为什么要使用
string[]portnames=SerialPort.GetPortNames()此处。
您只需使用CimProperties:

using (var session = CimSession.Create(null)) {
    var ports = session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM WIN32_SerialPort");

    var portsDescriptions = ports.Select(p =>
        $"{p.CimInstanceProperties["DeviceID"].Value} - {p.CimInstanceProperties["Caption"].Value}");

    // If you actually need to materialize a List<T>...
    portsDescriptions.ToList().ForEach(Console.WriteLine);
}
因此,不是:

var session = CimSession.Create(null);
您可以将其称为:

// LocalHost, default permissions
var session = CreateSession(null); 
或者根据需要传递域、用户名和密码(作为字符*)

var session = CimSession.Create(null);
// LocalHost, default permissions
var session = CreateSession(null);