2

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

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语句,这段代码被包裹进去了。

4

1 回答 1

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

于 2012-08-21T12:05:43.130 回答