2009-11-20 69 views
0

我用下面的代碼獲取邏輯驅動器:獲取邏輯驅動器

string[] strDrives = Environment.GetLogicalDrives(); 

但是當我想通過它來迭代,發生異常時,與消息:

Drive Not Ready 

我怎樣才能準備就緒驅動器?

回答

7

使用DriveInfo確定驅動器是否準備就緒。

foreach (var oneDrive in strDrives) 
{ 
    var drive = new DriveInfo(oneDrive) 
    if (drive.IsReady) 
    { 
     // Do something with the drive... 
    } 
} 
+0

+1 AH-這比我的好得多的解決方案! –

1

這也可以,當然可以使用LINQ實現:

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

我傾向於做:

List<DriveInfo> driveInfo = new List<DriveInfo>(from drive in DriveInfo.GetDrives() where drive.IsReady select drive);