How to get the MAC ID of a system using C #

I am creating a C # application and I want to get the system MAC id. I found a lot of code snippets, but they either give the wrong answers or throw exceptions. I am not sure which piece of code gives the correct answer. Can someone provide me with the exact code snippet that retrieves the MAC id?

+6
c #
source share
2 answers

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; } 
+10
source share

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

and iterate over each interface, getting the MAC address for each of them.

Another way would be to use a control 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
source share

All Articles