how to find the free percentage of a drive in c#
how to find the perce开发者_运维技巧ntage of the drive in c#
for example
if c: is 100 gb and the used space is 25 gb the free percentage should be 75%
Use the DriveInfo
class, like this:
DriveInfo drive = new DriveInfo("C");
double percentFree = 100 * (double)drive.TotalFreeSpace / drive.TotalSize;
If you want to get the free space available on any UNC path (possibly a partition mounted to a directory, or a share), you will have to resort to calling the Windows API.
class Program
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
static void Main(string[] args)
{
ulong available;
ulong total;
ulong free;
if (GetDiskFreeSpaceEx("C:\\", out available, out total, out free))
{
Console.Write("Total: {0}, Free: {1}\r\n", total, free);
Console.Write("% Free: {0:F2}\r\n", 100d * free / total);
}
else
{
Console.Write("Error getting free diskspace.");
}
// Wait for input so the app doesn't finish right away.
Console.ReadLine();
}
}
You might want to use the available bytes instead of free bytes, depending on your needs:
lpFreeBytesAvailable: A pointer to a variable that receives the total number of free bytes on a disk that are available to the user who is associated with the calling thread. If per-user quotas are being used, this value may be less than the total number of free bytes on a disk.
Assuming you are talking about free drive space, not directories, check out the DriveInfo class.
You can get info on all the drives:
DriveInfo[] drives = DriveInfo.GetDrives();
and then iterate over the array until you find the drive you are interested in:
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Free space on {0}: {1}", d.Name, d.TotalFreeSpace);
}
I think you are referring to partitions. IF that is the case, this should help.
精彩评论