需添加引用:System.Management.dll
/// <summary>
/// 获取本机第一个索引的网卡MAC
/// </summary>
/// <returns></returns>
public string GetMacAddress()
{
string mac = "" ;
System.Management.ManagementClass mc;
mc = new System.Management.ManagementClass( " Win32_NetworkAdapterConfiguration " );
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
// 可以使用 mo.GetText(System.Management.TextFormat.Mof); 获取所有值
if (mo[ " IPEnabled " ].ToString().Equals( " True " ))
{
/// /IPSubnet = "255.255.255.255",可能为拨号连接(MAC一般为:00-53-45-00-00-00)
if (mo[ " IPSubnet " ] != null )
{
// 记录是否为无效地址
bool isInvalid = false ;
string [] ipSubnets = ( string [])mo[ " IPSubnet " ];
foreach ( string ipSubnet in ipSubnets)
{
if (ipSubnet.Equals( " 255.255.255.255 " ))
{
isInvalid = true ;
break ;
}
}
if ( ! isInvalid)
{
// 获取第一个MAC
mac = mo[ " MacAddress " ].ToString();
break ;
}
}
}
}
return mac;
}