12.14. Querying Information for All Drives on a System
Problem
Your application needs to know if a drive (HDD, CD drive, DVD drive, etc.) is available and ready to be written to and/or read from. Additionally, it would be nice to know if you have enough available free space on the drive to write information to.
Solution
Use the various properties in the DriveInfo
class as shown here:
public static void DisplayAllDriveInfo() { foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.IsReady) { Console.WriteLine("Drive " + drive.Name + " is ready."); Console.WriteLine("AvailableFreeSpace: " + drive.AvailableFreeSpace); Console.WriteLine("DriveFormat: " + drive.DriveFormat); Console.WriteLine("DriveType: " + drive.DriveType); Console.WriteLine("Name: " + drive.Name); Console.WriteLine("RootDirectory.FullName: " + drive.RootDirectory.FullName); Console.WriteLine("TotalFreeSpace: " + drive.TotalFreeSpace); Console.WriteLine("TotalSize: " + drive.TotalSize); Console.WriteLine("VolumeLabel: " + drive.VolumeLabel); } else { Console.WriteLine("Drive " + drive.Name + " is not ready."); } } }
This code will display something like the following, though of course each system is different and the results will vary:
Drive C:\ is ready. AvailableFreeSpace: 143210795008 DriveFormat: NTFS DriveType: Fixed Name: C:\ RootDirectory.FullName: C:\ TotalFreeSpace: 143210795008 TotalSize: 159989886976 VolumeLabel: Vol1 Drive D:\ is ready. AvailableFreeSpace: 0 DriveFormat: UDF DriveType: CDRom Name: D:\ ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.