Encode and Decode Mac address from UUID using C#

2k Views Asked by At

I need to generate UUID for my Machine Mac address. Also i want extract the mac address from UUID.

I know we can use below two methods for encoding and decoding. But it will generate the encrypted string only not UUID.

Encode:

System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(plainTextBytes));

Decode:

System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(base64EncodedData));

But for my requirement i want to generate(encode) the UUID and extract(decode) the mac address . How to do this in C# code?

1

There are 1 best solutions below

0
On

You can get the MAC address using the following code. From our tests it will return null on about 1.3% of machines (probably some form of virtual machine or something very locked down).

MAC Address of first IP enabled device

    public static string  GetMACAddress()
    {
        try
        {
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
            {
                using (ManagementObjectCollection moc = mc.GetInstances())
                {
                    if (moc != null)
                    {
                        foreach (ManagementObject mo in moc)
                        {
                            try
                            {
                                Trace.WriteLine(mo["Index"] + " Mac " + mo["Caption"] + " : " + mo["MacAddress"] + " Enabled " + (bool)mo["IPEnabled"]);
                                if (mo["MacAddress"] != null && mo["IPEnabled"] != null && (bool)mo["IPEnabled"] == true)
                                {
                                    return mo["MacAddress"].ToString();
                                }
                            }
                            finally
                            {
                                mo.Dispose();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Trace.TraceWarning("Failed to read DiskID\r\n" + ex.Message);
        }
        return null;
    }