Topics like health, travel, finance, home, living, education and careers | Media Search Home

Calculate a computer drive"s free space with C# code

When our C# application fetches computer drive information, data about the disk"s size and free space is returned in bytes. While precise, those values are not easy to read and understand for our users. Other ways to show disk information is the percentage of free disk space or to report sizes in megabytes (MBs) or gigabytes (GBs). Let"s see how we get those values in C#.

IN THIS ARTICLE:

  • Access drive information and disk capacity with C# code
  • Example: calculate the free disk space percentage in C#
    • Example method to calculate the free disk space
    • Example extension method to calculate the percentage of free space
  • Example: calculate a drive"s disk space in GBs and MBs
  • Summary
# Access drive information and disk capacity with C# code

To get drive information in our C# application we use the DriveInfo class from the System.IO namespace (Asad & Ali, 2017; Stephens, 2014). A single DriveInfo object models one computer drive (Stephens, 2014). Through that object we can access the drive"s information, like its name label, type of drive, and the drive"s root directory.

Other data we can fetch from the DriveInfo class is the drive"s capacity, like free space amount or total size. We use the following three properties for that (Microsoft Docs, n.d.; Stephens, 2014):

  • The AvailableFreeSpace returns the drive"s available free space in bytes.
  • The TotalFreeSpace property returns the drive"s total free space.
  • And the TotalSize property returns the drive"s total capacity (that is, used and free space) in bytes.

The above three properties all require a ready and accessible drive. We can check if a drive is ready with the IsReady property. Or, when we access a drive that may be disconnected while our app runs, handle inaccessible computer drives with try/catch code blocks.

The TotalFreeSpace property returns the drive"s entire free space while AvailableFreeSpace takes drive quotas into account. That makes the latter property a better measure of the available free space. See the difference between TotalFreeSpace and AvailableFreeSpace for more.

To make sense of the above three properties and see how we can use them in our application"s code, let"s explore two examples. The first console application below calculates the percentage of free disk space a drive has. In the second example we convert a drive"s free disk space in bytes into megabytes (MBs) and gigabytes (GBs).

# Example: calculate the free disk space percentage in C#

To calculate the percentage of free space a computer drive has, we have to do a couple of things:

  • Create an instance for that drive with the DriveInfo class from the System.IO namespace.
  • Fetch the drive"s total size, which we get with the TotalSize property from that class.
  • Then get the drive"s free space, for which we can use the AvailableFreeSpace property.
  • After that we divide the free space by the drive"s total size to see what percentage of free disk space we have.

The console application example below shows how we implement these steps in C# code:

using System; using System.IO; class Kodify_Example { static void Main() { // Create a DriveInfo instance of the D:\ drive DriveInfo dDrive = new DriveInfo("D"); // When the drive is accessible.. if (dDrive.IsReady) { // Calculate the percentage free space double freeSpacePerc = (dDrive.AvailableFreeSpace / (float)dDrive.TotalSize) * 100; // Ouput drive information Console.WriteLine("Drive: {0} ({1}, {2})", dDrive.Name, dDrive.DriveFormat, dDrive.DriveType); Console.WriteLine("\tFree space:\t{0}", dDrive.AvailableFreeSpace); Console.WriteLine("\tTotal space:\t{0}", dDrive.TotalSize); Console.WriteLine("\n\tPercentage free space: {0:0.00}%.", freeSpacePerc); } Console.WriteLine("\nPress a key to close this window.."); Console.ReadKey(); } }

On my computer this example program shows that the D:\ drive has just over two thirds of free space:

Drive: D:\ (NTFS, Fixed) Free space: 167283777536 Total space: 250056704000 Percentage free space: 66,90%. Press a key to close this window..

Now let"s see how we got this output. First we make an instance of the DriveInfo class for the D:\ drive:

DriveInfo dDrive = new DriveInfo("D");

Then we check whether the computer drive is ready with an if statement. If it is, we query the drive"s properties for information:

if (dDrive.IsReady) { double freeSpacePerc = (dDrive.AvailableFreeSpace / (float)dDrive.TotalSize) * 100; Console.WriteLine("Drive: {0} ({1}, {2})", dDrive.Name, dDrive.DriveFormat, dDrive.DriveType); Console.WriteLine("\tFree space:\t{0}", dDrive.AvailableFreeSpace); Console.WriteLine("\tTotal space:\t{0}", dDrive.TotalSize); Console.WriteLine("\n\tPercentage free space: {0:0.00}%.", freeSpacePerc); }

The IsReady property returns true when a drive is ready and accessible. We check its value before we fetch other DriveInfo properties because some of those properties depend on a ready drive. If the drive is not ready to be queried, those properties trigger an inaccessible drive exception.

The first thing we do inside the if statement is calculate the percentage of free disk space. For that we divide the drive"s available free space (AvailableFreeSpace) with its total size (TotalSize). Then we multiple that value with 100 to get the percentage, and then store it in the freeSpacePerc double variable.

Note that we explicitly cast the TotalSize property to a float value. The reason for this is that both AvailableFreeSpace and TotalSize return an integer, and with integer division C# throws away the remainder of division (Liberty & MacDonald, 2009). Else when AvailableFreeSpace / TotalSize would normally be 0.45, C# returns 0 instead.

After we calculated the percentage of free space we call the Console.WriteLine() method to print the drive"s name (Name), file system format (DriveFormat), and kind of drive (DriveType). We also output the number of bytes returned by the AvailableFreeSpace and TotalSize properties. Then in the last line of the if statement we print the percentage of free disk space (freeSpacePerc).

# Example method to calculate the free disk space

When we calculate the percentage of free space more than once in our application, writing the above code over and over becomes a bore. Plus it doesn"t give code that"s easy to maintain. An alternative is to rewrite the code into a method that we can simply call to get a drive"s free space percentage.

Here"s how that method can look:

private double PercentageFreeSpace(string driveLetter) { try { DriveInfo drive = new DriveInfo(driveLetter); return (drive.AvailableFreeSpace / (double)drive.TotalSize) * 100; } catch { // Return -1 when the drive is not accessible (gives an `IOException`) // or when the drive letter is invalid, in which case `DriveInfo()` generates // an error of type `ArgumentException`. return -1; } }

This method returns the percentage of free space for the driveLetter string argument we pass it. Inside the method there"s a try/catch code to block handle inaccessible computer drives. In the try portion we make an instance of the DriveInfo class with DriveInfo(). Then we calculate that drive"s percentage of free space and return the outcome.

By the way, this method does assume that your code already referenced the System.IO namespace. If that isn"t the case, you"ll need to prefix the DriveInfo class with that namespace.

Here"s how we use this method to get the free space percentage of the C:\ drive:

Console.WriteLine("Free space % of C: " + PercentageFreeSpace("C"));
# Example extension method to calculate the percentage of free space

An alternative to the above method is to create an extension method that returns the percentage of free a particular DriveInfo instance has. That makes it possible to fetch a drive"s free disk space like any other property from the DriveInfo class.

Here"s how such an extension method looks:

public static class MyExtensions { public static double FreeSpacePercentage(this DriveInfo drive) { return (drive.AvailableFreeSpace / (double)drive.TotalSize) * 100; } }

To use this method we first create a DriveInfo object. Then we call that method on the object, provided the drive is ready:

DriveInfo dDrive = new DriveInfo("D"); if (dDrive.IsReady) { Console.WriteLine("Percentage of free space on D: {0}", dDrive.FreeSpacePercentage()); }
# Example: calculate a drive"s disk space in GBs and MBs

Let"s look at another way to use a drive"s space information. The AvailableFreeSpace, TotalFreeSpace, and TotalSize properties from the DriveInfo class return their values in bytes (Microsoft Docs, n.d.). But easier-to-understand values would be megabytes (MBs) and gigabytes (GBs). So let"s turn those bytes into MBs and GBs.

To go from bytes to other measurement units for computer space, we"ll need to consider the following (Wikipedia, 2017):

  • One terabyte (TB) is 1024 gigabytes. One of those gigabytes (GBs) is 1024 megabytes big. A single megabyte (MB) is 1024 kilobytes. And each kilobyte (KB) contains 1024 bytes.
  • Or in other words: 1 terabyte contains 1024^4 bytes. One gigabyte holds 1024^3 bytes, and 1024^2 bytes go into a single megabyte. And a single kilobyte contains 1024 bytes.

Say our computer drive has 20,000,000 bytes of free space. Because 1,048,576 (1024 * 1024) bytes go in a megabyte, our disk has 20,000,000 / 1,048,576 = 19.07 MB of free disk space. In the same way we can calculate how many kilobytes, gigabytes, and terabytes there are in a certain amount of bytes.

Now let"s translate this information into actual C# code. The console application example below outputs a drive"s used and total space in GBs and MBs:

using System; using System.IO; class Kodify_Example { static void Main() { // We use these constants to convert bytes to megabytes and gigabytes const double BytesInMB = 1048576; const double BytesInGB = 1073741824; Console.WriteLine("Computer drive sizes in MBs and GBs:"); // Go through each of the computer's drives foreach (DriveInfo drive in DriveInfo.GetDrives()) { // Skip to next loop cycle when drive is not ready if (!drive.IsReady) continue; Console.WriteLine("\nDrive: {0} ({1}, {2})", drive.Name, drive.DriveType, drive.DriveFormat); // Show the used and total size in MB and GB, with two decimals Console.WriteLine(" Used space:\t{0:0.00} MB\t{1:0.00} GB", (drive.TotalSize - drive.TotalFreeSpace) / BytesInMB, (drive.TotalSize - drive.TotalFreeSpace) / BytesInGB); Console.WriteLine(" Total size:\t{0:0.00} MB\t{1:0.00} GB", drive.TotalSize / BytesInMB, drive.TotalSize / BytesInGB); } Console.WriteLine("\nPress a key to close this window.."); Console.ReadKey(); } }

The output that this application generates on my computer is:

Computer drive sizes in MBs and GBs: Drive: C:\ (Fixed, NTFS) Used space: 102195,07 MB 99,80 GB Total size: 114371,00 MB 111,69 GB Drive: D:\ (Fixed, NTFS) Used space: 78949,86 MB 77,10 GB Total size: 238472,66 MB 232,88 GB Drive: E:\ (Removable, FAT32) Used space: 94,72 MB 0,09 GB Total size: 242,53 MB 0,24 GB Press a key to close this window..

Now let"s explore the program"s code. First we make two constants:

const double BytesInMB = 1048576; const double BytesInGB = 1073741824;

The BytesInMB constant tells how many bytes go in a megabyte, while BytesInGB says how many bytes we need for one GB.

We declare these constants as double values even though they hold integers. We do so because we"ll use these values later when we divide an integer value. And when we divide two integers, C# throws away the fractional portion of the outcome. To prevent that from happening we make double constants instead of int ones.

The next piece of program code iterates through the computer"s drives:

foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (!drive.IsReady) continue; Console.WriteLine("\nDrive: {0} ({1}, {2})", drive.Name, drive.DriveType, drive.DriveFormat); Console.WriteLine(" Used space:\t{0:0.00} MB\t{1:0.00} GB", (drive.TotalSize - drive.TotalFreeSpace) / BytesInMB, (drive.TotalSize - drive.TotalFreeSpace) / BytesInGB); Console.WriteLine(" Total size:\t{0:0.00} MB\t{1:0.00} GB", drive.TotalSize / BytesInMB, drive.TotalSize / BytesInGB); }

This foreach loop goes through all elements returned by DriveInfo.GetDrives(). That method returns an array with all drives the computer has. With the drive DriveInfo loop variable we represent a single drive during each iteration through the loop.

In the loop we first have an if statement see whether the current drive is not (!) ready. We get that drive state with the IsReady property. When the drive is not ready to be queried and accessed, we execute the continue keyword to skip the current loop cycle. That also means that later code in the loop works with a ready computer drive.

That other code first has the Console.WriteLine() method print the drive"s name (Name), kind of drive (DriveType), and its file system format (DriveFormat).

Then we output the drive"s used space in MBs and GBs. After that we output the drive"s used space in MBs and GBs. For that we first subtract the drive"s free space (TotalFreeSpace) from its total size (TotalSize). Then we divide that byte amount with the BytesInMB or BytesInGB constant. Next we have Console.WriteLine() print those used disk spaces with two decimals.

The last bit of loop code output the drive"s total size. For that we divide the drive"s TotalSize property with the BytesInMB or BytesInGB constant to get the total space in MBs and GBs. Then we print that information to the console window with Console.WriteLine().

# Summary

We access computer drive information in C# with an instance of the DriveInfo class. Once we have such an object we can query various properties for drive information. TotalSize, for instance, returns the drive"s total capacity in bytes. And with the AvailableFreeSpace and TotalFreeSpace properties we get the drive"s free space in bytes.

A large bytes value is, however, hard to read and comprehend. Luckily we can also represent a drive"s space in other ways. To see a computer drive"s free space percentage we divide AvailableFreeSpace with TotalSize. And to know the number of megabytes (MBs) or gigabytes (GBs) used we can divide one of those DriveInfo properties with 1,048,576 or 1,073,741,824. Keep in mind that when we divide two integers, C# throws away the decimal value. The solution to that is to cast to a float or double.

References

Asad, A. & Ali, H. (2017). The C# Programmer"s Study Guide (MCSD). New York, NY: Apress.

Liberty, J. & MacDonald, B. (2009). Learning C# 3.0: Master the Fundamentals of C# 3.0. Sebastopol, CA: O’Reilly Media.

Microsoft Docs (n.d.). DriveInfo Class. Retrieved on November 9, 2017, from https://docs.microsoft.com/en-us/dotnet/api/system.io.driveinfo?view=netframework-4.7.1

Stephens, R. (2014). C# 5.0 Programmer Reference. Indianapolis, IN: John Wiley & Sons.

Wikipedia (2017, November 23). Binary prefix. Retrieved on November 30, 2017, from https://en.wikipedia.org/wiki/Binary_prefix

Last updated on December 1, 2018 (published December 30, 2017).
# Related C# tutorials
  • How to check with C# code if a computer drive is ready to access?

    We fetch computer drive info with C#‘s DriveInfo class. Some data requires a ready drive. The IsReady property says whether a drive is ready or not.

  • How to get and change a computer drive"s volume label with C#?

    C# can change a drive"s volume label. For that we first make an instance of the DriveInfo class. Then we update that drive"s VolumeLabel property.

  • Get drive information in C# with the DriveInfo class

    We access computer drive information in C# with a DriveInfo object. We use the DriveInfo() constructor or the DriveInfo.GetDrives() method for that.

  • Computer drive information in C#: fetch the drive"s root directory and folders

    We access computer drive information with C#‘s DriveInfo class. With that class’ RootDirectory property we access the drive"s top-level directories.

  • How to programmatically filter and query computer drives in C#?

    C#‘s DriveInfo.GetDrives() method returns all computer drives. With LINQ extension methods and lambda expressions we can filter those programmatically.

« All C# computer drives articles


Email: contact@about.com.vn - Phone: 818.333.007 - Website: Media Search Home
Copyright © 2007 - Noos. All rights reserved