2010-07-01 170 views
2

我已经发现这个代码来获得一个MAC地址,但它返回一个长字符串,不包括':'。获取MAC地址C#

是否可以添加':'或分割字符串并自己添加它?

这里是代码:

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。

任何想法?

谢谢。

回答

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; 
     } 
+1

这是否提供可靠的MAC地址?因为我遇到了虚拟问题。 – Crazyd22 2010-07-01 11:30:03

+0

是的,它为我工作 – 2010-07-01 11:31:20

+0

是的完美,谢谢! – Crazyd22 2010-07-01 11:31:51

0

使用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("-"); 
     } 
    } 
+0

地址在当前上下文中不存在? – Crazyd22 2010-07-01 11:26:41

+1

这是一个例子。显然你必须用你正在使用的变量替换地址变量。 – Sjoerd 2010-07-01 11:42:03

0
function string GetSplitedMacAddress(string macAddresses) 
{ 
    for (int Idx = 2; Idx <= 15; Idx += 3) 
    { 
     macAddresses = macAddresses.Insert(Idx, ":"); 
    } 

    return macAddresses; 
} 
+0

这是行不通的,返回相同的值 – Crazyd22 2010-07-01 11:28:03

+0

这项工作我测试,结果是00:E0:EE:00:EE:00 – Svisstack 2010-07-01 11:28:25

8

可以使用BitConverter.ToString()方法:

var hex = BitConverter.ToString(nic.GetPhysicalAddress().GetAddressBytes()); 
hex.Replace("-", ":"); 
+0

对我来说最好的解决方案... – Paya 2010-07-01 11:48:23

1

你可以n使用此代码(使用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()); 
} 
3

使用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更多那么您只能通过"x2"而不是"X2"

+0

您可能需要在.Select()之后使用.ToArray()来编译它。 – Andrew 2010-07-01 11:46:33

+0

@Andrew:谢谢,最初我使用了.NET 4.0,其中'String.Join'有超负荷接受'IEnumerable '的参数。 更新我的代码以包含'.ToArray()' – Regent 2010-07-01 13:46:08