我发现此代码可以获取MAC地址,但是它返回一个长字符串,并且不包含':'。
是否可以添加':'或拆分字符串并将其自己添加?
代码如下:
private object GetMACAddress()
{
string macAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
它返回值00E0EE00EE00,而我希望它显示类似00:E0:EE:00:EE:00的值。
有什么想法吗?
谢谢。
答案 0 :(得分:4)
我正在使用以下代码以所需的格式访问mac地址:
public string GetSystemMACID()
{
string systemName = System.Windows.Forms.SystemInformation.ComputerName;
try
{
ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
ManagementObjectCollection theCollectionOfResults = theSearcher.Get();
foreach (ManagementObject theCurrentObject in theCollectionOfResults)
{
if (theCurrentObject["MACAddress"] != null)
{
string macAdd = theCurrentObject["MACAddress"].ToString();
return macAdd.Replace(':', '-');
}
}
}
catch (ManagementException e)
{
}
catch (System.UnauthorizedAccessException e)
{
}
return string.Empty;
}
或者您可以使用Join
方法,如下所示:
return string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());
答案 1 :(得分:1)
using System;
using System.Text;
class Program
{
static void Main()
{
Console.WriteLine(MACify("00E0EE00EE00"));
}
static string MACify(string input)
{
var builder = new StringBuilder(input);
for(int i=builder.Length-2; i>0; i-=2)
{
builder.Insert(i,':');
}
return builder.ToString();
}
}
输出:
00:E0:EE:00:EE:00