当c#中没有互联网连接时,有没有办法获取计算机的mac地址? 我能够在连接时获得但在离线时无法获得。但强烈的是,我需要为我的工作提供mac地址。
我的在线代码;
var macAddr =
(from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()).FirstOrDefault();
答案 0 :(得分:24)
来自WMI:
public static string GetMACAddress1()
{
ManagementObjectSearcher objMOS = new ManagementObjectSearcher("Select * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMOS.Get();
string macAddress = String.Empty;
foreach (ManagementObject objMO in objMOC)
{
object tempMacAddrObj = objMO["MacAddress"];
if (tempMacAddrObj == null) //Skip objects without a MACAddress
{
continue;
}
if (macAddress == String.Empty) // only return MAC Address from first card that has a MAC Address
{
macAddress = tempMacAddrObj.ToString();
}
objMO.Dispose();
}
macAddress = macAddress.Replace(":", "");
return macAddress;
}
来自System.Net命名空间:
public static string GetMACAddress2()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
//IPInterfaceProperties properties = adapter.GetIPProperties(); Line is not required
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
} return sMacAddress;
}
略微修改
答案 1 :(得分:3)
您可以在C#中使用WMI(System.Management
)来获取包含Win32_NetworkAdapter
属性的MACAddress
列表。
http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394216(v=vs.85).aspx