我正在开发一个安装程序项目,我需要将文件提取到磁盘。如何使用c#计算/查找硬盘上可用的磁盘空间?
答案 0 :(得分:9)
使用System.IO.DriveInfo
课程。有两个选项可供选择......一个考虑了磁盘配额的选项:
var drive = new DriveInfo("c");
long freeSpaceInBytes = drive.AvailableFreeSpace;
并且只提供总可用空间:
var drive = new DriveInfo("c");
long freeSpaceInBytes = drive.TotalFreeSpace;
答案 1 :(得分:9)
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);
}
}
}
}
答案 2 :(得分:2)
您也可以使用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"]);
}
}
}
}
}
答案 3 :(得分:0)
你需要关心吗?只需将文件写入磁盘并根据需要处理错误 - 假设您必须实现回滚,以防万一发生与空间无关的事情,所以只需将“无磁盘空间”视为您需要的另一个错误回滚。
更新:如果您来这里正确回答这个问题,请发表评论。