WMI获取磁盘信息
时间:2010-12-20 来源:aquariusgx

{
foreach (ManagementObject drive in new ManagementObjectSearcher(
"select * from Win32_DiskDrive").Get())
{
// associate physical disks with partitions
string type = drive["Caption"].ToString();
foreach (ManagementObject partition in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"]
+ "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
Console.WriteLine("Partition=" + partition["Name"]);
// associate partitions with logical disks (drive letter volumes)
foreach (ManagementObject disk in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
+ partition["DeviceID"]
+ "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
MessageBox.Show(type + "-->" + disk["Name"].ToString());
}
}
}
}
http://blog.csdn.net/FlyingColors_Snow/archive/2007/06/19/1657820.aspx
附上我刚写好的代码:

{
foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive").Get())
{
Console.Write(drive["Name"].ToString());
Console.Write(" 容量:" + (Convert.ToDouble(drive["Size"]) / (1024 * 1024 * 1024)).ToString("f2") + "G");
Console.Write(" 接口:" + drive["InterfaceType"].ToString());
Console.WriteLine(" 类型:" + drive["MediaType"].ToString());
double size = 0; //分区容量
double percentage = 0; //磁盘使用率
foreach (ManagementObject partition in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"]
+ "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
Console.WriteLine("Partition=" + partition["Name"].ToString());
Console.WriteLine(" 说明:" + drive["Caption"].ToString());
foreach (ManagementObject disk in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
+ partition["DeviceID"]
+ "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
Console.WriteLine(" 盘符:" + disk["Name"].ToString());
Console.WriteLine(" 容量:" + (Convert.ToDouble(disk["Size"])/(1024 * 1024 * 1024)).ToString("f2") + "G");
Console.WriteLine(" 剩余容量:" + (Convert.ToDouble(disk["FreeSpace"])/(1024 * 1024 * 1024)).ToString("f2") + "G");
Console.WriteLine(" 使用率:" + (100-((Convert.ToDouble(disk["FreeSpace"]))) * 100 / (Convert.ToDouble(disk["Size"]))).ToString("f2") + "%");
size += Convert.ToDouble(disk["Size"]) / (1024 * 1024 * 1024);
}
}
percentage = (size * 100) / (Convert.ToDouble(drive["Size"]) / (1024 * 1024 * 1024));
if (Convert.ToDouble(drive["Size"]) != 0)
{
Console.WriteLine("磁盘使用率:" + percentage.ToString("f2") + "%");
}
else
{
Console.WriteLine("磁盘容量为:0");
}
Console.WriteLine();
}
功能截图:
(磁盘使用率:划分成分区的部分视作已全部使用。)
相关阅读 更多 +