Arunachalam
Arunachalam

Reputation: 6087

how to find the free percentage of a drive in c#

how to find the percentage 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%

Upvotes: 3

Views: 5724

Answers (4)

Thorarin
Thorarin

Reputation: 48506

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.

Upvotes: 5

npinti
npinti

Reputation: 52185

I think you are referring to partitions. IF that is the case, this should help.

Upvotes: 0

Simon P Stevens
Simon P Stevens

Reputation: 27509

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);
}

Upvotes: 1

SLaks
SLaks

Reputation: 888167

Use the DriveInfo class, like this:

DriveInfo drive = new DriveInfo("C");
double percentFree = 100 * (double)drive.TotalFreeSpace / drive.TotalSize;

Upvotes: 15

Related Questions