C#完成獲得磁盤空間年夜小的辦法。本站提示廣大學習愛好者:(C#完成獲得磁盤空間年夜小的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成獲得磁盤空間年夜小的辦法正文
本文實例講述了C#完成獲得磁盤空間年夜小的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
辦法一:應用System.IO.DriveInfo.GetDrives辦法來獲得
///
/// 獲得指定驅動器的空間總年夜小(單元為B)
///
/// 只需輸出代表驅動器的字母便可 (年夜寫)
///
public static long GetHardDiskSpace(string str_HardDiskName)
{
long totalSize= new long();
str_HardDiskName=str_HardDiskName +":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
totalSize = drive.TotalSize / (1024 * 1024 * 1024);
}
}
return totalSize;
}
///
/// 獲得指定驅動器的殘剩空間總年夜小(單元為B)
///
/// 只需輸出代表驅動器的字母便可
///
public static long GetHardDiskFreeSpace(string str_HardDiskName)
{
long freeSpace = new long();
str_HardDiskName = str_HardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
freeSpace = drive.TotalFreeSpace / (1024 * 1024 * 1024);
}
}
return freeSpace;
}
辦法二:應用ManagementClass("Win32_LogicalDisk")來獲得
List<Dictionary<string, string>> diskInfoDic = new List<Dictionary<string, string>>();
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks = diskClass.GetInstances();
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#法式設計有所贊助。