C#实现获取磁盘空间大小的方法

2019-12-26 11:25:06王旭

foreach(ManagementObject disk in disks)
{
 Dictionary<string, string> diskInfo = new Dictionary<string, string>();
 try
 {
     // 磁盘名称
     diskInfo["Name"] =disk["Name"].ToString();
     // 磁盘描述
     diskInfo["Description"]=disk["Description"].ToString();
     // 磁盘总容量,可用空间,已用空间
     if (System.Convert.ToInt64(disk["Size"]) > 0)
     {
  long totalSpace = System.Convert.ToInt64(disk["Size"]) / MB;
  long freeSpace = System.Convert.ToInt64(disk["FreeSpace"]) / MB;
  long usedSpace = totalSpace - freeSpace;
       diskInfo["totalSpace"]=totalSpace.ToString();
  diskInfo["usedSpace"]=usedSpace.ToString();
  diskInfo["freeSpace"]=freeSpace.ToString();
     }
     diskInfoDic.Add(diskInfo);
 }
 catch(Exception ex)
 {
     Throw ex;
 }
}

 

希望本文所述对大家的C#程序设计有所帮助。