Wednesday, April 8, 2009

Display drive information using DriveInfo Class

DriveInfo class in .NET Framework is very useful class you can use to get information about the system drives. It has many properties and methods to query drive information such as drive type, drive format, total size or total free space. In the following Tutorial I will show you how to use this class in .NET Windows Application. Here is the list of the properties available in DriveInfo class.

NameDescription
AvailableFreeSpaceIndicates the amount of available free space on a drive.
DriveFormatGets the name of the file system, such as NTFS or FAT32.
DriveTypeGets the drive type.
IsReadyGets a value indicating whether a drive is ready.
NameGets the name of a drive.
RootDirectoryGets the root directory of a drive.
TotalFreeSpaceGets the total amount of free space available on a drive.
TotalSizeGets the total size of storage space on a drive.
VolumeLabelGets or sets the volume label of a drive.
Here is the code which you can use to access the properties of the driveInfo object. In the code below i have used the DriveInfo.GetDrives() function which will retrieves all logical drive names on a computer. You can use this information to iterate through the array and obtain information on the drives using other DriveInfo methods and properties. In the next statement the foreach loop is used to go through each object in the drive array. Then in the foreach loop if condition is place to check the IsReady property of the drive object. The IsReady indicates whether a drive is ready. For example, it indicates that a CD is in a CD drive or that a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and it is not ready, querying the drive using DriveInfo will raise an IOException.
DriveInfo[] drives = DriveInfo.GetDrives();
int intListCounter = 0;
foreach (DriveInfo drive in drives)
{
if (drive.IsReady)
{
lstDriveInfo.Items.Add(drive.Name);
lstDriveInfo.Items[intListCounter].SubItems.Add(drive.DriveFormat);
lstDriveInfo.Items[intListCounter].SubItems.Add(drive.TotalSize.ToString());
lstDriveInfo.Items[intListCounter].SubItems.Add(drive.TotalFreeSpace.ToString());
intListCounter++;
}
}
The DriveFormat property has either NTFS or FAT32 value, The formatting of the drive. And here is the list of enumeration of driveType enum.
Member Name
Description
UnknownThe type of drive is unknown.
NoRootDirectoryThe drive does not have a root directory.
RemovableThe drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
FixedThe drive is a fixed disk.
NetworkThe drive is a network drive.
CDRomThe drive is an optical disc device, such as a CD or DVD-ROM.
RamThe drive is a RAM disk.
Hope you get some understanding of the DriveInfo class. You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

No comments: