Search code examples
c#formattingmac-address

Formating a MAC Address in WinForms


Using one of my WinForms applications, I need to display the MAC address of the computer's various network adapters in a textbox.

This code works fine in getting the string:

public string AdapterAddress(string criteria)
{
    adapteraddress = (from nic in NetworkInterface.GetAllNetworkInterfaces()
                        where nic.Name == criteria
                        select nic.GetPhysicalAddress().ToString()
                        ).First();
    return adapteraddress;
}

but it outputs as

003E4B880D01

as opposed to

00:3E:4B:88:0D:01

I'd love it if I could use this directly for a command line "ipconfig /all"

I know I need to do something with taking the individual bytes and then joining them with String.Join(":", blah blah) but I can't quite get it.

Here's my messy way to do it, but I feel like I might run into some unexpected problems with this later:

public string AdapterAddress(string criteria)
{
    adapteraddress = (from nic in NetworkInterface.GetAllNetworkInterfaces()
                        where nic.Name == criteria
                        select nic.GetPhysicalAddress().ToString()
                        ).First();

    var tempaddress = SplitMacAddress(adapteraddress);
    adapteraddress = tempaddress;
    return adapteraddress;
}

public string SplitMacAddress(string macadress)
{
    for (int Idx = 2; Idx <= 15; Idx += 3)
    {
        macadress = macadress.Insert(Idx, ":");
    }
    return macadress;
}

Is there a cleaner solution that I'm missing?


Solution

  • You can format a PhysicalAddress instance as wished by taking the individual bytes and joining them in a string:

    string formattedAddress = String.Join(":", 
        adapteraddress.GetAddressBytes()
           .Select(b => b.ToString("X2"))
           .ToArray()
        );
    

    Note that you should leave out the .ToString() in your original query for this approach to work. Also, if you are on .NET 4, you can leave out the final .ToArray().