和大家分享下,互相学习一下吧。第一个获取方法好像获取不到mac地址,我用了第二种方法可以获取到。希望知道的可以说下为什么。

1,首先要添加引用: using System.Management ;
2,代码如下:

        /// <summary>
        /// 获取网卡硬件地址
      /// </summary>
        /// <returns>mac地址</returns>
        public string GetMacAddress()
                //获取网卡硬件地址
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                    if ((bool)mo["IPEnabled"])
                        mac = mo["MacAddress"].ToString();
                        break;
                moc = null;
                mc = null;
                return mac;
            catch
                return "";
        /// <summary>
        /// 获取网卡地址
      /// </summary>
        /// <returns>网卡地址</returns>
        private string GetMacAddressNew()
            const int MIN_MAC_ADDR_LENGTH = 12;
            string macAddress = string.Empty;
            long maxSpeed = -1;
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                string tempMac = nic.GetPhysicalAddress().ToString();
                if (nic.Speed > maxSpeed &&
                    !string.IsNullOrEmpty(tempMac) &&
                    tempMac.Length >= MIN_MAC_ADDR_LENGTH)
                    maxSpeed = nic.Speed;
                    macAddress = tempMac;
            return macAddress;