Getting logical drives

1.5k views Asked by At

I use the following code to get logical drives:

string[] strDrives = Environment.GetLogicalDrives();

but when I want to iterate through it, an exception occurs, with the message:

Drive Not Ready

How can I get just ready drives?

3

There are 3 answers

0
Kris Erickson On BEST ANSWER

Use DriveInfo to determine if the drive is ready.

foreach (var oneDrive in strDrives)
{
    var drive = new DriveInfo(oneDrive)
    if (drive.IsReady) 
    {
       // Do something with the drive...
    }
}
0
Fredrik Mörk On

This can also, of course, be achieved using Linq:

IEnumerable<DriveInfo> readyDrives = Environment.GetLogicalDrives()
    .Select(s => new DriveInfo(s))
    .Where(di => di.IsReady);
0
AudioBubble On

I would do the following:

string[] drives = DriveInfo.GetDrives()
                           .Where(drive => drive.IsReady)
                           .Select(drive => drive.Name)
                           .ToArray();

DriveInfo provides a static GetDrives method, which returns an array of DriveInfo (DriveInfo[]) instances, representing information about each drive.

The IsReady property of each instance returns a boolean value indicating whether the drive can be read from or written to.

Drives which are not 'ready' throw exceptions when used, and rightly so: you cannot perform any operations on a drive which is not ready, so the best approach would be to throw an exception if someone did so, informing them of their mistake.

In the above code, I use LINQ's Where extension to iterate through the drives and discard the ones which are not ready.

Next, in the Select method of the same nature, I retrieve each drive's Name property, which represents the drive letter, such as C:\ or D:\.

Finally, I call the ToArray method on the returned IEnumerable, which copies all of the elements in the enumerable into an array. I assume that you want the drive letters as an array.