1

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?

MicroVirus
  • 5,324
  • 2
  • 28
  • 53
JayNaz
  • 343
  • 1
  • 5
  • 24
  • Related: [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül May 13 '15 at 06:14
  • Which one do you want? There may be several adapters and you're just taking the first one, whatever it might be. Probably has nothing to do with the OS but the machine settings – Sami Kuhmonen May 13 '15 at 06:17
  • I want to get the Ethernet MAC address. The reason is, some desktop PCs haven't wireless adapters. – JayNaz May 13 '15 at 06:19

2 Answers2

1

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();
 } 
too_cool
  • 1,164
  • 8
  • 24
0

For the purpose of license activation I would actually recommend to use something else (or in addition) to the MAC address, as this is easily spoofed. Here is a very nice C# tutorial on how to obtain a "hardware fingerprint" that should solve your problem: http://www.codeproject.com/Articles/28678/Generating-Unique-Key-Finger-Print-for-a-Computer