views:

589

answers:

1

I want to get the mac address of the bluetooth device on the pc my application is running on.

I have tried the following:

private void GetMacAddress()
{
     string macAddresses = "";
     foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
     {
          if (nic.OperationalStatus == OperationalStatus.Up)
          {
               macAddresses += nic.GetPhysicalAddress().ToString();
               Console.WriteLine(macAddresses);
          }
     }
}

But the output does not match with 'ipconfig /all' in commandprompt. It does not print my blueotths mac address. Any solutions?

I am ready to parse the output I get from 'ipconfig /all' but how do I get the output as a String?

+1  A: 

Hi,

You can maybe use WMI to get the results. Herewith a link to a WMI solution that trails through the network devices.

I'm posting the code here in case the website is down, but all credit goes to the original author, PsychoCoder. Use WMI to get MAC Address in C#

And the code:

//Namespace reference
using System.Management;

/// <summary>
/// Returns MAC Address from first Network Card in Computer
/// </summary>
/// <returns>MAC Address in string format</returns>
public string FindMACAddress()
{
    //create out management class object using the
    //Win32_NetworkAdapterConfiguration class to get the attributes
    //af the network adapter
    ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
    //create our ManagementObjectCollection to get the attributes with
    ManagementObjectCollection objCol = mgmt.GetInstances();
    string address = String.Empty;
    //My modification to the code
    var description = String.Empty;
    //loop through all the objects we find
    foreach (ManagementObject obj in objCol)
    {
        if (address == String.Empty)  // only return MAC Address from first card
        {
            //grab the value from the first network adapter we find
            //you can change the string to an array and get all
            //network adapters found as well
            if ((bool)obj["IPEnabled"] == true)
            {
                address = obj["MacAddress"].ToString();
                description = obj["Description"].ToString();
            }
        }
       //dispose of our object
       obj.Dispose();
    }
    //replace the ":" with an empty space, this could also
    //be removed if you wish
    address = address.Replace(":", "");
    //return the mac address
    return address;
}

Be sure to include the reference to System.Management. In order for you to get the network device name, you can use the obj["Description"].ToString();

You can also have a look at MSDN regarding WMI, specifically to the Win32_NetworkAdapterConfiguration Class

Hope this helps.

Riaan
Cool! It worked. Thanks :)
bobjink
Glad I could help.
Riaan