2012-05-15 43 views
-1

使用我的一个WinForms应用程序,我需要在文本框中显示计算机各种网络适配器的MAC地址。在WinForms中格式化MAC地址

此代码工作正常在获取字符串:

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

但它输出作为

003E4B880D01 

,而不是

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

我喜欢它,如果我可以使用这直接用于命令行“ipconfig/all”

我知道我需要采取个别字节,然后加入他们与String.Join(“:”,等等等等),但我不能完全得到它。

这里是我凌乱的方式做到这一点,但我觉得我可能会稍后会碰到一些意想不到的问题:

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; 
} 

有没有办法,我缺少一个清晰的解决方案?

+3

只是一个命名的事情,我不会命名函数'SplitMacAddress'。这意味着你正在返回单个位。一个更好的名字可能是'FormatMacAddress'。 :)对不起,我无法帮助实际问题。 –

+1

你的方法究竟有什么问题? 003E4B880D01有什么问题,因为那是实际值。该值实际上并不是“00:3E:4B:88:0D:01”,这对我们人类来说是非常漂亮的。 –

+0

迭代感觉像是过度杀伤,如果我可以在一个区域完成所有操作,我希望稍后再添加一些检查,我觉得它会变得更加可重用。 –

回答

1

通过采取单个字节,并在字符串中加入他们的希望可以格式化PhysicalAddress实例:

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

请注意,您应该在原始查询离开了.ToString()这种方法工作。另外,如果您使用的是.NET 4,则可以省略最后的.ToArray()

+0

很好的解决方案,谢谢 –

0

最简单的方法:使用BitConverter

变种MAC = BitConverter.ToString(nic.GetPhysicalAddress()GetAddressBytes()。)替换( “ - ”, “:”);