问题
Can anybody help, how to get unallocated space information in a disk using C# ?
回答1:
If you want to know the total free space for a volume, you can use DriveInfo.AvailableFreeSpace
.
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
You can also use WMI to fetch information about partitions on the disk, using Win32_DiskPartition
and Win32_DiskDrive
:
Win32_DiskPartition: http://msdn.microsoft.com/en-us/library/aa394135%28VS.85%29.aspx
Win32_DiskDrive: http://msdn.microsoft.com/en-us/library/aa394132%28v=VS.85%29.aspx
You can use the DeviceID
field to identify which partition is on which disk, then use the StartOffset
and Size
fields to build a map of where the parititions are on the physical disk. Then just use the data from Win32_DiskDrive
to work out the whole disk size, and compute the remainder.
Here's an article on MSDN that should give you all the help you need in using WMI:
http://msdn.microsoft.com/en-us/library/ms257338.aspx
回答2:
Try with something like this:
using System.Linq;
using System.IO;
using System;
namespace DriveInfoExample
{
class Program
{
static void Main(string[] args)
{
// Check only for fixed drives
foreach (var di in DriveInfo.GetDrives().Where(d=>d.DriveType == DriveType.Fixed))
{
Console.WriteLine("Free space on drive {0}\t{1} bytes", di.Name, di.AvailableFreeSpace);
}
}
}
}
来源:https://stackoverflow.com/questions/7656857/how-to-get-unallocated-space-info-in-a-physical-disk