C# DriveInfo Examples

Use the DriveInfo class, calling DriveInfo.GetDrives and AvailableFreeSpace.
DriveInfo. Computers often have several drives. On Windows, these use letters such as C or D as names. In the .NET Framework, the DriveInfo class provides helper methods for checking these drives. We can get all drives.
Example. Often you may already know the drive name you want to access. Most Windows computers use the C drive name. In this program, we use the DriveInfo constructor and pass the one-character string literal "C".ConstructorString Literal

Then: We display the values returned by the properties on the DriveInfo instance. The free space properties return long values.


Output: The free space numbers are in bytes. It is possible to convert these to megabytes and gigabytes using custom helper methods.

Convert Bytes, Megabytes
C# program that uses DriveInfo using System; using System.IO; class Program { static void Main() { DriveInfo info = new DriveInfo("C"); // [1] Print sizes. Console.WriteLine(info.AvailableFreeSpace); Console.WriteLine(info.TotalFreeSpace); Console.WriteLine(info.TotalSize); Console.WriteLine(); // [2] Format and type. Console.WriteLine(info.DriveFormat); Console.WriteLine(info.DriveType); Console.WriteLine(); // [3] Name and directories. Console.WriteLine(info.Name); Console.WriteLine(info.RootDirectory); Console.WriteLine(info.VolumeLabel); Console.WriteLine(); // [4] Ready. Console.WriteLine(info.IsReady); } } Output 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. The DriveInfo.GetDrives method is available for this purpose. It 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.

C# program that gets all drives using System; using System.IO; class Program { static void Main() { // Print all drive names. var drives = DriveInfo.GetDrives(); foreach (DriveInfo info in drives) { Console.WriteLine(info.Name); } } } Output C:\ D:\
Summary. Helper methods such as DriveInfo are not usually needed in programs. But when they are needed, they make programs much easier to develop. The DriveInfo class can be combined with the DirectoryInfo and FileInfo classes.FileInfo
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls