Search code examples
c#windows-8windows-7wmimac-address

Get MAC Address using ManagementObjectSearcher


I am trying to develop a registration algorithm in C#. I used MAC address of the client machine to generate the request code. The function is shown below. But in Windows 7, This function shows a NullRererenceException in this line.

mac = mo["MACAddress"].ToString();

public string GetMACAddress()
{
      string mac = null;
      ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration");
      foreach (ManagementObject mo in mos.Get())
      {
           mac = mo["MACAddress"].ToString();
           break;
      }

      return mac;
}

What is the most reliable way to get MAC address, in Windows 7 and Windows 8, using C#, in order to develop an activation algorithm?


Solution

  • Not all object content the MAC address so need to check which one dose have the MAC

    you can do some thing like this

    string macAddress = String.Empty;
    foreach (ManagementObject mo in mos.Get())
     {
          object tempMacAddrObj = MO["MacAddress"];
    
        if (tempMacAddrObj == null) //Skip objects without a MACAddress
        {
            continue;
        }
        if (macAddress == String.Empty) // only return MAC Address from first card that has a MAC Address
        {
            macAddress = tempMacAddrObj.ToString();              
        }
        objMO.Dispose();
     }