以下是我在 C# 中通过 WMI 收集有关磁盘使用情况的信息:
private List<DiskInfo> GetDiskInfo()
{
List<DiskInfo> disks = new List<DiskInfo>();
SelectQuery query = new SelectQuery("SELECT Size, FreeSpace, Name, FileSystem FROM Win32_LogicalDisk WHERE DriveType = 3");
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = moSearcher.Get();
foreach (ManagementObject res in collection)
{
float size = Convert.ToSingle(res["Size"]) / 1024f;
float usedSpace = size - (Convert.ToSingle(res["FreeSpace"]) / 1024f);
DiskInfo di = new DiskInfo();
di.Name = res["Name"].ToString();
di.Size = ConvertVal(size);
di.UsedSpace = ConvertVal(usedSpace);
if (size > 0)
{
di.PercentUsed = ((usedSpace / size) * 100).ToString("N0");
}
else
{
di.PercentUsed = "0";
}
if (res["FileSystem"] != null)
{
di.FileSystem = res["FileSystem"].ToString();
disks.Add(di);
}
}
return disks;
}
// handles returning the correct units
private string ConvertVal(float value)
{
float K = value;
float M = value / 1024f;
float G = M / 1024f;
float T = G / 1024f;
string unit = "KB";
float val = K;
if (K >= 1024)
{
unit = "MB";
val = M;
}
if (M >= 1024)
{
unit = "GB";
val = G;
}
if (G >= 1024)
{
unit = "TB";
val = T;
}
return val.ToString("N2") + unit;
}
我主要将上面的代码与完整的 ComputerInfo 类结合使用,我可以每隔几秒在 ASP.NET MVC 服务上从 jQuery AJAX 调用该类,该服务将 JSON 返回到浏览器,并使用提供的数据动态构建页面。
这是我的 DiskInfo 类,用于使数据更易于显示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ComputerInfo.Models
{
public class DiskInfo
{
public string Name { get; set; }
public string Size { get; set; }
public string UsedSpace { get; set; }
public string PercentUsed { get; set; }
public string FileSystem { get; set; }
}
}
我希望这有帮助。如果您在答案中需要其他任何内容,请告诉我。