Home
C#
DriveInfo Examples
Updated Sep 7, 2023
Dot Net Perls
DriveInfo. Computers often have several drives—on Windows, these use letters such as C or D as names. The DriveInfo class provides helper methods for checking these drives.
C# method notes. With GetDrives() we can get an array of drives from a computer—this may be the most helpful DriveInfo method. The code is already debugged as it is part of .NET.
First example. Most Windows computers use the C drive name. In this program, we use the DriveInfo constructor and pass the one-character string literal "C."
Constructor
String Literal
Then We display the values returned by the properties on the DriveInfo instance. The free space properties return long values.
long, ulong
Detail The free space numbers are in bytes. It is possible to convert these to megabytes and gigabytes using custom helper methods.
Convert Bytes, Megabytes
using System; using System.IO; DriveInfo info = new DriveInfo("C"); // Print sizes. Console.WriteLine(info.AvailableFreeSpace); Console.WriteLine(info.TotalFreeSpace); Console.WriteLine(info.TotalSize); Console.WriteLine(); // Format and type. Console.WriteLine(info.DriveFormat); Console.WriteLine(info.DriveType); Console.WriteLine(); // Name and directories. Console.WriteLine(info.Name); Console.WriteLine(info.RootDirectory); Console.WriteLine(info.VolumeLabel); Console.WriteLine(); // Ready. Console.WriteLine(info.IsReady);
682166767616 682166767616 984045580288 NTFS Fixed C:\ C:\ OS True
Example 2. Sometimes a program will need to get an array of all the drives on the computer. DriveInfo.GetDrives returns an array of DriveInfo class instances.
Here We use the foreach-loop on the result of the GetDrives method. The code from the first example could be added to the loop.
foreach
using System; using System.IO; // Print all drive names. var drives = DriveInfo.GetDrives(); foreach (DriveInfo info in drives) { Console.WriteLine(info.Name); }
C:\ D:\
Summary. The DriveInfo class can be combined with the DirectoryInfo and FileInfo classes. This can improve file IO handling in certain programs.
FileInfo
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 7, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen