[C#]透過WMI取得CPU/網路卡資訊
以下兩段程式透過WMI來取得CPU與網路卡的資訊:
取得CPU編號:
public string GetCPUId()
{
string cpuInfo = String.Empty;
string temp=String.Empty;
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if(cpuInfo==String.Empty)
{// only return cpuInfo from first CPU
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
}
}
return cpuInfo;
}
取的網路卡MAC:
public ArrayList GetMACAddress()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
ArrayList MACAddress = new ArrayList();
foreach (ManagementObject mo in moc)
{
if (mo["MacAddress"] != null)
MACAddress.Add(mo["MacAddress"].ToString().Replace(":", ""));
mo.Dispose();
}
return MACAddress;
}
這部分若有多張網路卡,則會回傳多個位址,我們可以逐一判斷。
若要取得磁碟機的編號,可用下方這個function:
1 public string GetVolumeSerial(string strDriveLetter)
2 {
3 if( strDriveLetter=="" || strDriveLetter==null) strDriveLetter="C";
4 ManagementObject disk =
5 new ManagementObject("win32_logicaldisk.deviceid=\"" + strDriveLetter +":\"");
6 disk.Get();
7 return disk["VolumeSerialNumber"].ToString();
8 }
2 {
3 if( strDriveLetter=="" || strDriveLetter==null) strDriveLetter="C";
4 ManagementObject disk =
5 new ManagementObject("win32_logicaldisk.deviceid=\"" + strDriveLetter +":\"");
6 disk.Get();
7 return disk["VolumeSerialNumber"].ToString();
8 }
游舒帆 (gipi) 探索原力Co-founder,曾任TutorABC協理與鼎新電腦總監,並曾獲選兩屆微軟最有價值專家 ( MVP ),離開職場後創辦探索原力,致力於協助青少年培養面對未來的能力。認為教育與組織育才其實息息相關,都是在為未來儲備能量,2018年起成立為期一年的專題課程《職涯躍升的關鍵24堂課》,為培養台灣未來的領袖而努力。 |