NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface item in arr)
{
PhysicalAddress mac = item.GetPhysicalAddress();
}它返回值00E0EE00EE00,而我希望它显示类似00:E0:EE:00:EE:00的内容,但我需要使用.Net 4
有什么想法吗?
发布于 2012-12-08 14:17:14
可以使用string类的方法添加:
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发布于 2014-11-20 23:16:52
我知道这个问题已经回答了一段时间,但我只想澄清一下,首选的解决方案通常是为PhysicalAddress类创建一个可重用的扩展方法。由于它是一个简单的数据类,并且可能不会更改,因此出于可重用性的考虑,这样做更好。我将使用Lorenzo的示例,因为我最喜欢它,但您可以使用任何适合您的例程。
public static class PhysicalAddressExtensions
{
public static string ToString(this PhysicalAddress address, string separator)
{
return string.Join(separator, address.GetAddressBytes()
.Select(x => x.ToString("X2")))
}
}现在你可以像这样使用扩展方法:
NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface item in arr)
{
PhysicalAddress mac = item.GetPhysicalAddress();
string stringFormatMac = mac.ToString(":");
}请记住,PhysicalAddress.Parse只接受原始的十六进制或破折号分隔值,以防您想要将其解析回对象。因此,在解析之前剥离分隔符是很重要的。
发布于 2014-03-13 16:32:30
你可以这样做:
string macAddr = "AAEEBBCCDDFF";
var splitMac = SplitStringInChunks(macAddr);
static string SplitStringInChunks(string str)
{
for (int i = 2; i < str.Length; i += 3)
str = str.Insert(i, ":");
return str;
}https://stackoverflow.com/questions/13775037
复制相似问题