如何计算可用磁盘空间?

我正在开发一个安装程序项目,我需要将文件提取到磁盘。 如何使用c#计算/查找硬盘上可用的磁盘空间?

http://msdn.microsoft.com/en-us/library/system.io.driveinfo.totalfreespace.aspx

从链接复制

using System; using System.IO; class Test { public static void Main() { DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}", d.Name); Console.WriteLine(" File 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); } } } } 

使用System.IO.DriveInfo类。 有两个选项可用…一个考虑磁盘配额的选项:

 var drive = new DriveInfo("c"); long freeSpaceInBytes = drive.AvailableFreeSpace; 

并且只提供总空闲空间:

 var drive = new DriveInfo("c"); long freeSpaceInBytes = drive.TotalFreeSpace; 

您也可以使用WMI。

http://msdn.microsoft.com/en-us/library/windows/desktop/aa394173(v=vs.85).aspx

 using System; using System.Management; class Test { static void Main() { var moCollection = new ManagementClass("Win32_LogicalDisk").GetInstances(); foreach (var mo in moCollection) { if (mo["DeviceID"] != null && mo["DriveType"] != null && mo["Size"] != null && mo["FreeSpace"] != null) { // DriveType 3 = "Local Disk" if (Convert.ToInt32(mo["DriveType"]) == 3) { Console.WriteLine("Drive {0}", mo["DeviceID"]); Console.WriteLine("Size {0} bytes", mo["Size"]); Console.WriteLine("Free {0} bytes", mo["FreeSpace"]); } } } } } 

你需要关心吗? 只需将文件写入磁盘并根据需要处理错误 – 假设您必须实现回滚以防万一发生非空间相关的情况,所以只需将“无磁盘空间”视为您需要的另一个错误回滚。

更新:如果您来这里正确回答这个问题,请留下评论原因。