Inspecting the drives on the local PC using C# .NET
January 2, 2015 Leave a comment
It’s very simple to enumerate the drives on a Windows computer. The DriveInfo object has a GetDrives static method which returns an array of DriveInfo objects. A DriveInfo describes a drive through its properties. It is similar to the FileInfo class which in turn describes a file.
There are some properties that can only be extracted if the drive is ready, e.g. a CD-Rom drive. The following method prints the available drives:
DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { Console.WriteLine("Drive name: {0}", drive.Name); if (drive.IsReady) { Console.WriteLine("Total size: {0}", drive.TotalSize); Console.WriteLine("Total free space: {0}", drive.TotalFreeSpace); Console.WriteLine("Available free space: {0}", drive.AvailableFreeSpace); Console.WriteLine("Drive format: {0}", drive.DriveFormat); } else { Console.WriteLine("Device {0} is not ready.", drive.Name); } Console.WriteLine("Drive type: {0}", drive.DriveType); }
I got the following output:
DriveType can have the following values:
- CDRom: an optical drive such as a CD-ROM, DVD etc.
- Fixed: a fixed disk, quite often labelled as “C:\”
- Network: a mapped drive
- NoRootDirectory: a drive with no root directory
- Ram: a RAM drive
- Removable: a removable drive such as a pen-drive
- Unknown: a drive whose type could not be determined
Read all posts dedicated to file I/O here.