驱动器的C#循环挂起

时间:2012-08-21 11:51:49

标签: c# loops hang drive

我正在尝试查找驱动器的驱动器号(例如“C:\”)。 我知道驱动器的名称(例如“KINGSTON”),并将其存储在字符串drivename中。 sDir是保存结果的字符串。

DriveInfo[] drives = DriveInfo.GetDrives();

foreach (DriveInfo d in drives)
{
   MessageBox.Show(d.Name);
   if (d.VolumeLabel.Contains(drivename))
   {
      MessageBox.Show("Got Ya");
      sDir = d.Name;
      break;
   }
}

这段代码在我看来应该可以工作,但是,虽然我有6个驱动器(drives.Lengt也显示6个),它只循环3个,没有进入if(从不显示“得到你的“msgbox”,然后跳出if-sentence,这段代码被包裹起来。

1 个答案:

答案 0 :(得分:2)

DriveInfo.VolumeLabel可能会抛出异常,您必须正确处理它。 http://msdn.microsoft.com/library/system.io.driveinfo.volumelabel

DriveInfo[] drives = DriveInfo.GetDrives(); 

foreach (DriveInfo d in drives) 
{ 
   MessageBox.Show(d.Name);
   string volumeLabel = null;
   try
   {
     volumeLabel = d.VolumeLabel;
   }
   catch (Exception ex)
   {
     if (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
       MessageBox.Show(ex.Message);
     else
       throw;
   }
   if (volumeLabel != null && volumeLabel.Contains(drivename)) 
   { 
      MessageBox.Show("Got Ya"); 
      sDir = d.Name; 
      break; 
   } 
} 

您还可以查看DriveInfo.IsReady

相关问题