The idea here is to be able to find a USB serial port device connected during runtime, thus not knowing its port number, and use it in the application to retrieve information from the device.
string comportInfo = string.Empty;
using (var entitySearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%" + SerialPortToFind + "%'"))
{
using (var serialPortSearcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName"))
{
//testBase.SamplerWithCancel is like a for loop with exception control, a time between interations and amount of iterations to be made. It expects a true or false value to determine whether a desired condition is met. Failing to return a true value in the specified iterations throws an exception.
testBase.SamplerWithCancel(() =>
{
var portList = serialPortSearcher.Get().Cast<ManagementBaseObject>().ToList();
var matchingEntities = entitySearcher.Get().Cast<ManagementBaseObject>().First();
if (portList.Count != 0 && matchingEntities != null)
{
foreach (ManagementBaseObject port in portList)
{
if (port["InstanceName"].ToString().Contains(matchingEntities["DeviceID"].ToString()))
{
comportInfo = port["PortName"].ToString();
}
}
return true;
}
else
return false;
}, "Serial port not found", 3, 1500, 500, false, false);
}
}
The code works well, but I want to know where I can improve it to make it more resilient and less error prone.
I feel like using LINQ would be way more appropiate than what I did.