获取MAC地址C#

我发现此代码获取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; } 

您可以使用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("-"); } }