Printing out MAC address

Just trying to use string.Format() to convert system MAC address to text format. But it's not working:

byte[] MacAddr = new byte[6];

// this works, but rather clumzy
mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}",            
          MacAddr[0], MacAddr[1], MacAddr[2], MacAddr[3], MacAddr[4], MacAddr[5]);

// give me index error
mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", MacAddr);

Edit1: OK, I am wrong, but it seems string.format works for this guy's case with string[] .

I can see there is a overload method for string.format: Format(String, array<Object>[]()[]). Is it possble to create some form of byte[], that can be taken as this array<Object>[]()[] ?

5 answers

  • answered 2018-07-11 05:34 fubo

    the error occurs because you want to format 6 items but there is only 1 in your parameter list

    //6 parameters expected, only one "MacAddr" given
    mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", MacAddr); 

    here is a shorter version compared to your working approach

    mac = string.Join("-", MacAddr.Select(x => x.ToString("X2")));

  • answered 2018-07-11 05:39 Barr J

    This is because you specify a format with 6 parameters but provide only one:

    //expected 6 parameters, provided only one
    mac = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}", MacAddr); 

    if you are working with C# 6.0, you can also work with string interpolation:

     //string interpolation
        mac = $"{MacAddr[0]}:X2-{MacAddr[1]}:X2-{MacAddr[2]}:X2-{MacAddr[3]}:X2-{MacAddr[4]}:X2-{MacAddr[5]}:X2"; 

  • answered 2018-07-11 05:42 Gaurav Jalan

    There is only 1 parameter in your string.Format() function while it requires 6 parameters as per requirement. You can use String.Join for a better readable approach -

    mac = string.Join("-", MacAddr.Select(x => x.ToString(":X2")));

  • answered 2018-07-11 05:44 Toshi

    try BitConverter

    mac = BitConverter.ToString(MacAddr);

  • answered 2018-07-11 05:48 George Helyar

    BitConverter.ToString(byte[]) gets the exact string you want, although MAC addresses are usually separated by colons, not dashes.