
DriveInfo Class and DriveType Enumeration
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- DriveInfo
- Throws a DriveNotFoundException when querying a non-existent drive.
- AvailableFreeSpace returns the freeBytesForUser.
- TotalFreeSpace returns the freeBytes.
Examples
Get Drive Information
class Program
{
static void Main(string[] args)
{
DriveInfo a = new DriveInfo("a");
DriveInfo c = new DriveInfo("c");
WriteDriveInfo(a);
WriteDriveInfo(c);
}
private static void WriteDriveInfo(DriveInfo drive)
{
try
{
Console.WriteLine(string.Format("{0} ({1}): {2}", drive.DriveType, drive.DriveFormat, drive.VolumeLabel));
Console.WriteLine(string.Format("{0} / {1}", drive.TotalFreeSpace.Humanize(), drive.TotalSize.Humanize()));
}
catch (DriveNotFoundException dex)
{
Console.WriteLine(dex.Message);
}
}
}
public static class SizeExtensions
{
// Credits to http://blogs.interakting.co.uk/brad/archive/2008/01/24/C-Getting-a-user-friendly-file-size-as-a-string.aspx
public static string Humanize(this long bytes)
{
double s = bytes;
string[] format = new string[] { "{0} bytes", "{0} KB", "{0} MB", "{0} GB", "{0} TB", "{0} PB", "{0} EB", "{0} ZB", "{0} YB" };
int i = 0;
while (i < format.Length - 1 && s >= 1024)
{
s = (100 * s / 1024) / 100.0;
i++;
}
return string.Format(format[i], s.ToString("###,###,##0.##"));
}
}
Get All Drives
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
WriteDriveInfo(drive);
}
You May Also Like

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.



