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."
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.