C#获得本机物理网卡的MAC地址

public string GetMacAddressByNetworkInformation()
{
string key = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
string macAddress = string.Empty;
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (https://www.360docs.net/doc/ad8438575.html,workInterfaceType == NetworkInterfaceType.Ethernet
&& adapter.GetPhysicalAddress().ToString().Length!=0)
{
string fRegistryKey =key+adapter.Id+ "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 &&
fPnpInstanceID.Substring(0, 3) == "PCI")
{
macAddress = adapter.GetPhysicalAddress().ToString();
for (int i = 1; i < 6; i++)
{
macAddress = macAddress.Insert(3 * i - 1, ":");
}
break;
}
}

}
}
}
catch(Exception ex)
{
//这里写异常的处理
}
return macAddress;
}

相关文档
最新文档