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.
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.
Most Windows computers use the C drive name. In this program, we use the DriveInfo
constructor and pass the one-character string
literal "C."
DriveInfo
instance. The free space properties return long values.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
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.
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:\
The DriveInfo
class
can be combined with the DirectoryInfo
and FileInfo
classes. This can improve file IO handling in certain programs.