Obtain the COM port number mapped to the serial port
Background: Recently, due to project requirements, you need to operate the SMS cat. After the SMS cat is inserted into the computer, it will map the COM port based on the current PC status. Here, you need to dynamically obtain the COM port mapped by the SMS cat.
Programming Language C #:
The Code is as follows:
Public enum HardwareEnum
{
Win32_PnPEntity // all devices
}
/// <Summary>
/// Get the corresponding COM slogan
/// </Summary>
Private static string getComInfo (HardwareEnum hardType, string propkey)
{
List <string> deviceslist = new List <string> ();
StringBuilder comsb = new StringBuilder ();
Try
{
Using (ManagementObjectSearcher searcher = new ManagementObjectSearcher ("select * from" + hardType ))
{
Var hardInfos = searcher. Get ();
Foreach (var hardInfo in hardInfos)
{
Object deviceprop = hardInfo. Properties [propkey]. Value;
If (deviceprop! = Null & deviceprop. ToString (). Contains ("COM") // avoid null device value exceptions
{
Deviceslist. Add (hardInfo. Properties [propkey]. Value. ToString ());
}
}
Searcher. Dispose ();
}
String [] devicestemps = deviceslist. ToArray ();
Foreach (string device in devicestemps)
{
If (device. Contains ("AT") // The AT port must be operated on by the SMS cat.
{
Int index = device. IndexOf ("(");
String devicetemp = device. Substring (index + 4); // obtain the format as "3 )"
String comnum = devicetemp. Substring (0, devicetemp. Length-1); // obtain the corresponding COM port number.
Comsb. Append (comnum + "*"); // separate multiple values with the "*" sign.
}
}
String comsbstring = comsb. ToString ();
Return comsbstring. Substring (0, comsbstring. Length-1); // remove the last "*"
}
Catch
{
Return null;
}
Finally
{
Deviceslist = null;
}
}
/// <Summary>
/// Obtain the COM port number
/// </Summary>
Public static string getComNum ()
{
String comnums = getComInfo (HardwareEnum. Win32_PnPEntity, "name ");
Return comnums; // returns the composition of multiple COM numbers, which can be parsed here or at call time. Here, we will not repeat it too much.
}
Note: 1. You can use this method to obtain the COM port number you actually need to operate on.
2. Click "*" to splice the COM port number. You can parse the return value to determine that multiple SMS cats are connected at the current time for further operations.