0

I thought this would be simple. I need the path to a USB but since I dont know which letter it will be assigned I thought I just use the volume label which doesnt change. Here my simple code:

 var alldrives = DriveInfo.GetDrives();
 string destd = alldrives.Where(x => x.VolumeLabel.Equals("UB64")).First().Name;

This throws Io exception (device is unavailable) even though the usb is plugged in. Could somebody let me know why please?

In my view this is different from a full list, as I already have a type of address and just need to convert to full path as opposed to start from nothing.

nik
  • 1,672
  • 2
  • 17
  • 36
  • possible duplicate of [Get List of connected USB Devices](http://stackoverflow.com/questions/3331043/get-list-of-connected-usb-devices) – NoWar Apr 17 '15 at 19:36
  • @Dimi: i saw that but I would like to get the drive name if I know the volumelabel as opposed to a full list. I thought this must be a lot simpler... – nik Apr 17 '15 at 19:38
  • Take a look here https://social.msdn.microsoft.com/Forums/en-US/d2ad33a7-dd5f-42ed-bd55-c5b4102f7ba7/detection-usb-device-and-get-drive-letter?forum=csharplanguage or http://stackoverflow.com/questions/7222782/how-to-get-the-drive-letter-from-a-full-name-of-the-drive – NoWar Apr 17 '15 at 19:41
  • 2
    It simply means that while your USB stick may be available, other drives might not be, which means reading their volume label will fail. – Chris Apr 17 '15 at 19:43
  • @Chris: Great! so it fails not on the usb drive but on one of the others – nik Apr 17 '15 at 19:44

1 Answers1

0

Chris pointed me to the right answer. In case it helps anybody else here it is:

var alldrives = DriveInfo.GetDrives();
string destd="";
foreach (var drvs in alldrives)
{
    try
    {
          if (drvs.VolumeLabel.Equals("UB64"))
              destd = drvs.Name;
              break;
     }
     catch
     {
        continue;
     }
}

i.e. it is not the USB causing the error...

nik
  • 1,672
  • 2
  • 17
  • 36
  • 1
    Or to simplify: `var destd = DriveInfo.GetDrives().Single( d => d.IsReady && d.VolumeLabel == "UB64" ).Name;` That'll break horribly if there is no such drive though. – Chris Apr 17 '15 at 20:22
  • Or if there is more than one, for that matter. – Chris Apr 17 '15 at 20:25