开发者

How to get MAC ID of a system using C#

开发者 https://www.devze.com 2023-01-13 09:21 出处:网络
I am building a C# application and I want to fetch the MAC ID of the system. I have found many code snippets, but they either give wrong answers or throw exceptions. I am not sure which code snippet i

I am building a C# application and I want to fetch the MAC ID of the system. I have found many code snippets, but they either give wrong answers or throw exceptions. I am not sure which code snippet is giving the right answer. Can someone provide me the exact code snippet that开发者_StackOverflow fetches the MAC ID?


This will help you.

public string FetchMacId()
{
    string macAddresses = "";

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


System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

and iterate through each interface, getting the MAC address for each one.

Another way would be to use management object:

ManagementScope theScope = new ManagementScope("\\\\computerName\\root\\cimv2");
StringBuilder theQueryBuilder = new StringBuilder();
theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter");
ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString());
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

foreach (ManagementObject theCurrentObject in theCollectionOfResults)
{
    string macAdd = "MAC Address: " + theCurrentObject["MACAddress"].ToString();
    MessageBox.Show(macAdd);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消