sumit_batcoder
sumit_batcoder

Reputation: 3379

How to get MAC ID of a system using C#

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 fetches the MAC ID?

Upvotes: 6

Views: 7466

Answers (2)

Pankaj Mishra
Pankaj Mishra

Reputation: 20348

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

Upvotes: 11

Nissim
Nissim

Reputation: 6553

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

Upvotes: 0

Related Questions