0

I have this bit of code:

DriveInfo[] myDrives = DriveInfo.GetDrives();
foreach (DriveInfo myDrive in myDrives)
{
    if (myDrive.DriveType == DriveType.Removable)
    {
        string path = Convert.ToString(myDrive.RootDirectory);
        DirectoryInfo mydir = new DirectoryInfo(path);
        String[] dirs = new string[] {Convert.ToString(mydir.GetDirectories())};
        String[] files = new string[] {Convert.ToString(mydir.GetFiles())};

        foreach (var file in files)
        {
            File.SetAttributes(file, ~FileAttributes.Hidden);
            File.SetAttributes(file, ~FileAttributes.ReadOnly);
        }

        foreach (var dir in dirs)
        {
            File.SetAttributes(dir, ~FileAttributes.Hidden);
            File.SetAttributes(dir, ~FileAttributes.ReadOnly);
        }        
    }
}

I have a problem. It is trying the code for Floppy Disk drive first which and because no Floppy disk in it, it threw the error The device is not ready. How can I prevent that?

tshepang
  • 12,111
  • 21
  • 91
  • 136
p19lord
  • 33
  • 6
  • Sorry but questions asking for external tutorials are off-topic for SO... – Adriano Repetti Jul 25 '14 at 12:53
  • @AdrianoRepetti OK fine, would you please give me a code asset? – p19lord Jul 25 '14 at 12:56
  • Also asking for "code" (without describing what you first tried) is off-topic for SO! Please read FAQ for more details about what's on topic. BTW read/write files content and attributes on a USB device isn't different to do that on files stored in a SATA/SCSI/whatever attached media...you'd better to post code isn't working as expected! – Adriano Repetti Jul 25 '14 at 13:05
  • @AdrianoRepetti Sorry I didn't read that, so now I edited the question. – p19lord Jul 26 '14 at 18:06
  • Voted to reopen anyway: 1) first check myDrive.IsReady property (skip if false) and 2) always catch UnauthorizedAccessException and IOException, there are 1000 reasons that calls may fail (catch where more appropriate, each single function you're calling may fail for different reasons). I'd also (to make it easier) split that code in more functions. – Adriano Repetti Jul 26 '14 at 18:48

0 Answers0