使用ManagementObjectSearcher获取MAC地址

时间:2015-05-13 06:11:20

标签: c# windows-8 windows-7 wmi mac-address

我正在尝试用C#开发注册算法。我使用客户端机器的MAC地址来生成请求代码。功能如下所示。但在Windows 7中,此函数在此行中显示NullRererenceException

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;
}

在Windows 7和Windows 8中,使用C#获取MAC地址的最可靠方法是什么,以开发激活算法?

2 个答案:

答案 0 :(得分:1)

并非所有对象内容都是MAC地址,因此需要检查哪一个剂量具有MAC

你可以做这样的事情

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();
 } 

答案 1 :(得分:0)

出于许可证激活的目的,我实际上建议对MAC地址使用其他东西(或者另外),因为这很容易被欺骗。这是一个非常好的C#教程,介绍如何获得"硬件指纹"这应该可以解决您的问题:http://www.codeproject.com/Articles/28678/Generating-Unique-Key-Finger-Print-for-a-Computer

相关问题