c# - 如何获取系统的 MAC ID
问题描述
我发现此代码可以获取 MAC 地址,但它返回一个长字符串并且不包含“:”。
是否可以添加':'或拆分字符串并自己添加?
这是代码:
private object GetMACAddress()
{
string macAddresses = "";
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
它返回 00E0EE00EE00 的值,而我希望它显示类似 00:E0:EE:00:EE:00 的内容。
有任何想法吗?
谢谢。
解决方案
我正在使用以下代码以您想要的格式访问 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;
}
或者您可以使用Join
方法,如下所示:
return string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());
推荐阅读
- shader - 具有非均匀倾斜的Godot着色器?
- python - 自动点击器代码不起作用(第一个项目)
- go - 如何在我的 CLI 中获取用户选择的标志
- python - 构建具有不同扩展名选择的文件路径
- laravel - 修改供应商文件,Laravel
- python - 如何在不覆盖列值的情况下连接数据帧
- python - 如何使用交易机器人同时监控多个资产?
- java - 来自前端的第三方的 Rest API 请求设计
- docusignapi - DocuSign API 设置签名者语言不适用于第一个签名者
- ibm-doors - 使用 IBM DOORS 并需要 DXL 脚本将段落 ID 添加到链接