In order to get information about Serial Port devices, with System.Management
, we can do as described in Getting Serial Port Information:
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();
}
}
}
How can this be achieved using Microsoft.Management.Infrastructure
, I haven't managed to find examples and the documentation isn't detailed enough.
It's quite similar:
null
for LocalHost) and a CimCredential object (passing the usual UserName and Password for authentication, is necessary). This reflects System.Management'sConnectionOption
.QueryInstances()
returns an IEnumerble<CimInstance> objects (the good news is that no COM objects are returned here).As a note, you're skipping the ConnectionOption and EnumerationOptions in your WMI Query, which is not really good PERF-wise.
Your query can then be translated to:
I'm not sure why you use
string[] portnames = SerialPort.GetPortNames();
here.You can just use the CimProperties:
Unrelated, but could be useful: I suggest to build some methods to create a CimSession with more options. For example:
So, instead of:
You can call it as:
Or pass domain, Username and Password (as Char*), if needed.