Search code examples
c#loopsfreezedrive

C# loop for drives hangs


I am trying to find the drive letter ("C:\" for instance) of a drive. I know the name of the drive("KINGSTON" for instance), and store it in the string drivename. sDir is the string that holds the result.

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;
   }
}

This piece of code seems to me like it should work, though, eventhough i have 6 drives (drives.Lengt also shows 6), it only loops through 3 of them, without ever getting into the if (never shows the "got ya" msgbox), and then just jumps out of the if-sentence, this code is wrapped in.


Solution

  • DriveInfo.VolumeLabel might throw an exception, you must handle it properly. 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; 
       } 
    } 
    

    You could also check DriveInfo.IsReady.