0

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 Answers 3

6

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... } } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.