NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface item in arr)
{
PhysicalAddress mac = item.GetPhysicalAddress();
}
It returns the value of 00E0EE00EE00 whereas I want it to display something like 00:E0:EE:00:EE:00 but i need to use .Net 4
any ideas ?
You can use String.Insert method of string class to add :
string macAddStr = "00E0EE00EE00";
string macAddStrNew = macAddStr;
int insertedCount = 0;
for(int i = 2; i < macAddStr.Length; i=i+2)
macAddStrNew = macAddStrNew.Insert(i+insertedCount++, ":");
//macAddStrNew will have address 00:E0:EE:00:EE:00
I know this was answered a while ago, but I just wanted to clarify that the preferred solution is usually to create a reusable extension method for the PhysicalAddress class. Since it is a simple data class, and is likely not to change, this is better for reusability reasons. I will use Lorenzo's example because I like it the most, but you can use whichever routine suits you.
public static class PhysicalAddressExtensions
{
public static string ToString(this PhysicalAddress address, string separator)
{
return string.Join(separator, address.GetAddressBytes()
.Select(x => x.ToString("X2")))
}
}
Now you can just use the extension method from now on like this:
NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface item in arr)
{
PhysicalAddress mac = item.GetPhysicalAddress();
string stringFormatMac = mac.ToString(":");
}
Remember that the PhysicalAddress.Parse only accepts the RAW hex or dash separated values, in case you wanted to parse it back into an object. So stripping the separator character before you parse is important.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With