我发现此代码获取MAC地址,但它返回一个长字符串,不包含':'.
是否可以添加':'或拆分字符串并自行添加?
这是代码:
private object GetMACAddress()
{
string macAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
Run Code Online (Sandbox Code Playgroud)
它返回值00E0EE00EE00,而我希望它显示类似00:E0:EE:00:EE:00的内容.
有任何想法吗?
谢谢.
Pra*_*ana 10
我正在使用以下代码以您想要的格式访问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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用BitConverter.ToString()方法:
var hex = BitConverter.ToString( nic.GetPhysicalAddress().GetAddressBytes() );
hex.Replace( "-", ":" );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7006 次 |
| 最近记录: |