DriveInfo Examples
This page was last reviewed on 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."
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 7, 2023 (edit).
© 2007-2024 Sam Allen.