Thursday, March 11, 2010

DriveInfo Properties

The DriveInfo class class models a drive and allows one to query info about the drives in the system. While writing the code to exercise this class I was tripped up by a "gotcha". Trying to query the volume label of a a CD drive when there is not a CD raises an exception. To keep the source code simple below, it was decided o check to see if the drive is ready (A CD drive will report not ready if there is there is not a CD)
// GetDrives returns an array of all the drives on the system
DriveInfo[] drives = DriveInfo.GetDrives();

Console.WriteLine("\n-------------------------------------\n");
        
//Please keep these two lines if you would like to use this code on your site
Console.WriteLine("DriveInfo Example");
Console.WriteLine("Created by Charles Cozad, http://www.mctscertification.blogspot.com");

Console.WriteLine("\n-------------------------------------\n");

foreach (DriveInfo drive in drives)
{
    Console.WriteLine("Drive Name: {0}", drive.Name);
    // We check if the drive is ready because calling some of
    // the calls can throw exceptions (such as for a CD drive
    // without a CD in it)
    if (drive.IsReady)
    {
          Console.WriteLine("Drive Label: {0}", drive.VolumeLabel);
          Console.WriteLine("Drive Type: {0}", drive.DriveType);
          Console.WriteLine("Drive Formt: {0}", drive.DriveFormat);
          Console.WriteLine("Available Free Space: {0}", drive.AvailableFreeSpace);
          Console.WriteLine("Total Free Space: {0}", drive.TotalFreeSpace);
          Console.WriteLine("Total Space: {0}", drive.TotalSize);
          Console.WriteLine("\n+++++++++++++++++++++++++++++\n");
     }
     else
     {
          Console.WriteLine("Drive info skipped, because the drive is not ready");
     }
}


Additional Resources
DriveInfo Class (Microsoft)

No comments:

Post a Comment