DriveInfo Class and DriveType Enumeration
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
Overview
- DriveInfo
- Will not work on non-existent drives.
- 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 (var drive in DriveInfo.GetDrives())
{
WriteDriveInfo(drive);
}
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



