如何获取系统的 MAC ID

How to get MAC ID of a system

我发现此代码可以获取 MAC 地址,但它 returns 是一个长字符串并且不包含“:”。

是否可以添加“:”或拆分字符串并自己添加?

代码如下:

private object GetMACAddress()
{
    string macAddresses = "";

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            macAddresses += nic.GetPhysicalAddress().ToString();
            break;
        }
    }

    return macAddresses;
 }

它 returns 00E0EE00EE00 的值,而我希望它显示类似 00:E0:EE:00:EE:00.

的内容

有什么想法吗?

谢谢。

我正在使用以下代码以您想要的格式访问 mac 地址:

public string GetSystemMACID()
        {
            string systemName = System.Windows.Forms.SystemInformation.ComputerName;
            try
            {
                ManagementScope theScope = new ManagementScope("\\" + Environment.MachineName + "\root\cimv2");
                ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
                ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
                ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

                foreach (ManagementObject theCurrentObject in theCollectionOfResults)
                {
                    if (theCurrentObject["MACAddress"] != null)
                    {
                        string macAdd = theCurrentObject["MACAddress"].ToString();
                        return macAdd.Replace(':', '-');
                    }
                }
            }
            catch (ManagementException e)
            {
                           }
            catch (System.UnauthorizedAccessException e)
            {

            }
            return string.Empty;
        }

或者您可以使用 Join 方法,如下所示:

return string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());
using System;
using System.Text;

class Program
{
    static void Main()
    {
        Console.WriteLine(MACify("00E0EE00EE00"));
    }

    static string MACify(string input)
    {
        var builder = new StringBuilder(input);
        for(int i=builder.Length-2; i>0; i-=2)
        {
            builder.Insert(i,':');
        }

        return builder.ToString();
    }
}

输出:

00:E0:EE:00:EE:00