How do I get COM port where my mobile device connected through a bluetooth stick? I can already get the name of the device eg. 'Nokia C2-01' with device.DeviceName
using the 32feet library
but how can I make it look like this? "Nokia c2-01 connected through COM7"
?
First, you will need to get the device address using:
string comPort = GetBluetoothPort(device.DeviceAddress.ToString());
if(!string.IsNullOrWhiteSpace(comPort))
{
// enter desired output here
}
The GetBluetoothPort() method will look something like this:
using System.Management;
private string GetBluetoothPort(string deviceAddress)
{
const string Win32_SerialPort = "Win32_SerialPort";
SelectQuery q = new SelectQuery(Win32_SerialPort);
ManagementObjectSearcher s = new ManagementObjectSearcher(q);
foreach (object cur in s.Get())
{
ManagementObject mo = (ManagementObject)cur;
string pnpId = mo.GetPropertyValue("PNPDeviceID").ToString();
if (pnpId.Contains(deviceAddress))
{
object captionObject = mo.GetPropertyValue("Caption");
string caption = captionObject.ToString();
int index = caption.LastIndexOf("(COM");
if (index > 0)
{
string portString = caption.Substring(index);
string comPort = portString.
Replace("(", string.Empty).Replace(")", string.Empty);
return comPort;
}
}
}
return null;
}
This will return the port name ie COM7
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.