10

当c#中没有互联网连接时,有什么方法可以获取计算机的mac地址?当我有连接时我能够获得,但当我离线时无法获得。但是我强烈需要我的工作的mac地址。

我的在线代码;

var macAddr =
      (from nic in NetworkInterface.GetAllNetworkInterfaces()
       where nic.OperationalStatus == OperationalStatus.Up
       select nic.GetPhysicalAddress().ToString()).FirstOrDefault();
4

2 回答 2

26

来自 WMI:

public static string GetMACAddress1()
{
    ManagementObjectSearcher objMOS = new ManagementObjectSearcher("Select * FROM Win32_NetworkAdapterConfiguration");
    ManagementObjectCollection objMOC = objMOS.Get();
    string macAddress = String.Empty;
    foreach (ManagementObject objMO in objMOC)
    {
        object tempMacAddrObj = objMO["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();
    }
    macAddress = macAddress.Replace(":", "");
    return macAddress;
}

从 System.Net 命名空间:

public static string GetMACAddress2()
{
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
    String sMacAddress = string.Empty;
    foreach (NetworkInterface adapter in nics)
    {
        if (sMacAddress == String.Empty)// only return MAC Address from first card  
        {
            //IPInterfaceProperties properties = adapter.GetIPProperties(); Line is not required
            sMacAddress = adapter.GetPhysicalAddress().ToString();
        }
    } return sMacAddress;
}

稍微修改了如何获取系统的 MAC 地址 - C-Sharp Corner

于 2013-04-03T09:50:29.017 回答
3

您可以在 C# ( ) 中使用 WMISystem.Management来获取Win32_NetworkAdapter包含MACAddress属性的 's 列表。

http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394216(v=vs.85).aspx

于 2013-04-03T09:46:58.943 回答