在编写工具检查硬盘信息时,总结常用到的类:
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 256
AddTextBox("Description: " + Convert.ToString(mo.Properties["Description"].Value)); //diskdriver
AddTextBox("InterfaceType: " + Convert.ToString(mo.Properties["InterfaceType"].Value)); //scsi
AddTextBox("MediaType: " + Convert.ToString(mo.Properties["MediaType"].Value)); //fixed hard disk
string 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);
}
}