上方廣告

2009年3月3日 星期二

讀取硬碟序號、主機板序號、MAC位址(使用 WMI)

透過WMI,我們可以很方便的取得主機的各種資訊,下列舉例三種取得硬體資訊的方法,使用前必須先加入using System.Management;命名空間

硬碟序號
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2","SELECT * FROM Win32_PhysicalMedia");

foreach (ManagementObject queryObj in searcher.Get())
{
  MessageBox.Show(queryObj["SerialNumber"].ToString());
}


主機板序號 (注意此方法在Windows2000上失效,會出現錯誤訊息,調用API取得可解決)
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2","SELECT * FROM Win32_BaseBoard");

foreach (ManagementObject queryObj in searcher.Get())
{
  MessageBox.Show(queryObj["SerialNumber"].ToString());
}


MAC位址 有幾種常用的取法
//方法一
ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryCollection = query.Get();
strMAC = "======第一個Fucntion===========\n\r";
foreach (ManagementObject mo in queryCollection)
{
  if (mo["IPEnabled"].ToString() == "True")
    strMAC += mo["MacAddress"].ToString() + "\n\r";
}

//方法二
strMAC += "======第二個Fucntion===========\n\r";
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
PhysicalAddress MAC;
MAC = nics[0].GetPhysicalAddress(); //<--- data-blogger-escaped-anagementobject="" data-blogger-escaped-ddress="" data-blogger-escaped-foreach="" data-blogger-escaped-from="" data-blogger-escaped-in="" data-blogger-escaped-mac="" data-blogger-escaped-managementobjectsearcher="" data-blogger-escaped-n="" data-blogger-escaped-pre="" data-blogger-escaped-queryobj="" data-blogger-escaped-r="" data-blogger-escaped-root="" data-blogger-escaped-searcher.get="" data-blogger-escaped-searcher="new" data-blogger-escaped-strmac="" data-blogger-escaped-ucntion="==========\n\r" data-blogger-escaped-win32_networkadapter="">