我正在构建一个C#应用程序,我想获取系统的MAC ID。我找到了很多代码片段,但是他们要么给出错误的答案,要么抛出异常。我不确定哪个代码段正在给出正确的答案。有人能为我提供获取MAC ID的确切代码段吗?
答案 0 :(得分:10)
这会对你有所帮助。
public string FetchMacId()
{
string macAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
答案 1 :(得分:0)
System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
并遍历每个接口,获取每个接口的MAC地址。
另一种方法是使用管理对象:
ManagementScope theScope = new ManagementScope("\\\\computerName\\root\\cimv2");
StringBuilder theQueryBuilder = new StringBuilder();
theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter");
ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString());
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
ManagementObjectCollection theCollectionOfResults = theSearcher.Get();
foreach (ManagementObject theCurrentObject in theCollectionOfResults)
{
string macAdd = "MAC Address: " + theCurrentObject["MACAddress"].ToString();
MessageBox.Show(macAdd);
}