get system free disk space in csharp

To get the free space of the system disk on a Windows machine using C#, you can use the DriveInfo class in the System.IO namespace.

main.cs
DriveInfo drive = new DriveInfo("C:\\");
long freeSpace = drive.TotalFreeSpace;
80 chars
3 lines

In the code above, we create a DriveInfo object for the system disk with the path "C:\\" and then retrieve the TotalFreeSpace in bytes as a long integer.

If you want to format the bytes as a human-readable string (e.g. "4.2 GB"), you can use the following method:

main.cs
public static string FormatBytes(long bytes)
{
    if (bytes < 0) return "-" + FormatBytes(-bytes);
    if (bytes == 0) return "0 B";
    string[] sizes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
    int i = (int)Math.Floor(Math.Log(bytes, 1024));
    decimal value = (decimal)bytes / (decimal)Math.Pow(1024, i);
    return $"{value:F2} {sizes[i]}";
}
366 chars
10 lines

Now you can use the FormatBytes method to print the free disk space in a human-readable format:

main.cs
Console.WriteLine($"Free space: {FormatBytes(freeSpace)}");
60 chars
2 lines

related categories

gistlibby LogSnag