题
我找到了此代码以获取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: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;
}
其他提示
您可以使用 bitconverter.tostring() 方法:
var hex = BitConverter.ToString( nic.GetPhysicalAddress().GetAddressBytes() );
hex.Replace( "-", ":" );
使用linq只需替换
macAddresses += nic.GetPhysicalAddress().ToString();
// Produces "00E0EE00EE00"
和
macAddresses += String.Join(":", nic.GetPhysicalAddress()
.GetAddressBytes()
.Select(b => b.ToString("X2"))
.ToArray());
// Produces "00:E0:EE:00:EE:00"
你也可以玩 ToString
参数,例如,如果您喜欢 00:e0:ee:00:ee:00
多于 00:E0:EE:00:EE:00
那你可以通过 "x2"
代替 "X2"
.
您可以使用此代码(使用LINQ):
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
// ....
private static string GetMACAddress()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
return AddressBytesToString(nic.GetPhysicalAddress().GetAddressBytes());
}
return string.Empty;
}
private static string AddressBytesToString(byte[] addressBytes)
{
return string.Join(":", (from b in addressBytes
select b.ToString("X2")).ToArray());
}
function string GetSplitedMacAddress(string macAddresses)
{
for (int Idx = 2; Idx <= 15; Idx += 3)
{
macAddresses = macAddresses.Insert(Idx, ":");
}
return macAddresses;
}
使用 GetAddressBytes
方法:
byte[] bytes = address.GetAddressBytes();
for(int i = 0; i< bytes.Length; i++)
{
// Display the physical address in hexadecimal.
Console.Write("{0}", bytes[i].ToString("X2"));
// Insert a hyphen after each byte, unless we are at the end of the
// address.
if (i != bytes.Length -1)
{
Console.Write("-");
}
}
//MAC地址
var macAddress = NetworkInterface.GetAllNetworkInterfaces();
var getTarget = macAddress[0].GetPhysicalAddress();
不隶属于 StackOverflow