1

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"?

Roman R.
  • 68,205
  • 6
  • 94
  • 158
Dac
  • 210
  • 3
  • 19

1 Answers1

0

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 i.e. COM7

jimebe
  • 93
  • 1
  • 4
  • What if the device exposes multiple comports, is there any way to map each comport to a specific `ServiceRecord`? – Peter Jul 26 '17 at 13:38