Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting MAC Address C#

Tags:

c#

mac-address

I have found this code to get a MAC address, but it returns a long string and doesn't include ':'.

Is it possible to add in the ':' or split up the string and add it it myself?

here is the code:

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

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

    return macAddresses;
 }

It returns the value of 00E0EE00EE00 whereas I want it to display something like 00:E0:EE:00:EE:00.

Any ideas?

Thanks.

like image 736
Crazyd22 Avatar asked Nov 28 '22 18:11

Crazyd22


1 Answers

i am using following code to access mac address in format you want :

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;
        }
like image 173
Pranay Rana Avatar answered Dec 05 '22 22:12

Pranay Rana