2010-08-30 59 views
6

我正在構建一個C#應用程序,我想獲取系統的MAC ID。我發現了很多代碼片段,但它們要麼給出錯誤的答案,要麼拋出異常。我不確定哪個代碼片段給出了正確的答案。有人可以提供準確的代碼片段來獲取MAC ID嗎?如何獲得使用C#的系統的MAC ID

回答

10

這會幫助你。

public string FetchMacId() 
{ 
    string macAddresses = ""; 

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) 
    { 
     if (nic.OperationalStatus == OperationalStatus.Up) 
     { 
      macAddresses += nic.GetPhysicalAddress().ToString(); 
      break; 
     } 
    } 
    return macAddresses; 
} 
+0

這一次是很大的。這對我來說可以。謝謝Pankaj – 2010-08-30 06:56:14

+1

爲什麼字符串連接和'break'?爲什麼你不能在循環內部寫'return nic.GetPhysicalAddress()。ToString()'並去除變量? – Timwi 2010-08-30 07:41:32

0

System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

,並通過各接口迭代,得到的MAC地址每一個。

另一種方法是使用管理對象:

ManagementScope theScope = new ManagementScope("\\\\computerName\\root\\cimv2"); 
StringBuilder theQueryBuilder = new StringBuilder(); 
theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter"); 
ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString()); 
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery); 
ManagementObjectCollection theCollectionOfResults = theSearcher.Get(); 

foreach (ManagementObject theCurrentObject in theCollectionOfResults) 
{ 
    string macAdd = "MAC Address: " + theCurrentObject["MACAddress"].ToString(); 
    MessageBox.Show(macAdd); 
} 
相關問題