2010年9月8日 星期三

C# 取得本機Mac Address

取得本機MAC Address, 格式為 Dictionary<MAC名稱, MAC位址)


private Dictionary<string, string> GetMacAddress()
{
   Dictionary<string, string> dicMAC = new Dictionary<string, string>();
   StringBuilder strbui = new StringBuilder();
   NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
  
   foreach (NetworkInterface adapter in nics)
   {
      PhysicalAddress address = adapter.GetPhysicalAddress();
      byte[] bytes = address.GetAddressBytes();
     
      for (int i = 0; i < bytes.Length; i++)
      {
         // Display the physical address in hexadecimal.
         strbui.AppendFormat("{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)
         {
            strbui.Append("-");
         }
         else
         {
            dicMAC.Add(adapter.Name, strbui.ToString());
            strbui = new StringBuilder();
         }
      }
   }
   return dicMAC;
}