在編寫工具檢查硬盤信息時,總結常用到的類:
Win32_DiskDrive
? 這個用了檢查整個硬盤的信息,如果電腦只有一個硬盤,那只顯示一條信息。參考如下代碼,AddTextBox為自定義顯示函數。(MSDN class 查詢:https://msdn.microsoft.com/en-us/library/aa394132(v=vs.85).aspx)
ManagementClass mc = new ManagementClass("Win32_DiskDrive");
ManagementObjectCollection moc = mc.GetInstances(); ?
foreach (ManagementObject mo in moc){AddTextBox(">>硬盤詳細信息----------------------------------------------------------"); AddTextBox("Model: " + Convert.ToString(mo.Properties["Model"].Value)); //name stata 256AddTextBox("Description: " + Convert.ToString(mo.Properties["Description"].Value)); //diskdriverAddTextBox("InterfaceType: " + Convert.ToString(mo.Properties["InterfaceType"].Value)); //scsiAddTextBox("MediaType: " + Convert.ToString(mo.Properties["MediaType"].Value)); //fixed hard diskstring strSize=Convert.ToString( mo.Properties["Size"].Value);AddTextBox("size:"+Convert.ToString( mo.Properties["Size"].Value)+"KB");var aaa = Convert.ToString( mo.Properties["Size"].Value);UInt64 bbb=UInt64.Parse(aaa);totalsise = (float)Math.Round(bbb / 1000 / 1000 / 1000.0, 3);totalsise2 = (float)Math.Round(bbb / 1024 / 1024 / 1024.0, 3);AddTextBox("size(除1000): " + totalsise.ToString()+"GB");AddTextBox("size(除1024): " + totalsise2.ToString() + "GB");}
Win32_Volume
當檢查C盤,D盤或光盤,可以用到這個class,DriverLetter顯示C:\,D:\等。通過查看DriverType的數值能判定當前盤符是哪種類型。參考:https://msdn.microsoft.com/en-us/library/aa394515(v=vs.85).aspx
ManagementObjectSearcher deviceList = new ManagementObjectSearcher("Select DriveLetter, DeviceID,DriveType,Name from Win32_Volume ");foreach (ManagementObject device in deviceList.Get()){string name = Convert.ToString(device.GetPropertyValue("DriveLetter"));string DriveType = Convert.ToString(device.GetPropertyValue("DriveType"));if (DriveType == "3" && name != ""){//..}}
DriveInfo.GetDrives()
這個函數功能和上面Win32_Volume功能類似,但沒Win32_Volume那么多信息查詢。優點在于用起來方便,易懂,官方已經給出例子:(https://msdn.microsoft.com/zh-cn/library/system.io.driveinfo.getdrives.aspx)
DriveInfo[] allDrives = DriveInfo.GetDrives();foreach (DriveInfo d in allDrives){Console.WriteLine("Drive {0}", d.Name);Console.WriteLine(" Drive type: {0}", d.DriveType);if (d.IsReady == true){Console.WriteLine(" Volume label: {0}", d.VolumeLabel);Console.WriteLine(" File system: {0}", d.DriveFormat);Console.WriteLine(" Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);Console.WriteLine(" Total available space: {0, 15} bytes",d.TotalFreeSpace);Console.WriteLine(" Total size of drive: {0, 15} bytes ",d.TotalSize);}}