21

How to check the drive is exists in the system from the given string in WPF. I have tried the following

Ex: FileLocation.Text = "K:\TestDrive\XXX";

if (!Directory.Exists(FileLocation.Text))
{
         MessageBox.Show("Invalid Directory", "Error", MessageBoxButton.OK);
         return;
}

It is checking full path but it should check "K:\" from the text. Could you please guide me

EDIT 1: "K:\TestDrive\XXX" is not static

EDIT 2: I tried the below, in my system i'm having 3 drives C, D and E but it showing false.

Environment.SystemDirectory.Contains("D").ToString(); = "False"
Ponmalar
  • 6,871
  • 10
  • 50
  • 80
  • 2
    Please make sure your samples have reasonable C# code. I.e. `"K:\Test..."` is somewhat suspicious string constant: should be `@"K:\Test..."` or `"K:\\Test..."`, checking for `true`/`false` does not require call for `ToString` and definitely not case sensitive comparison with strange `; =` operator. – Alexei Levenkov Jun 27 '13 at 05:37
  • @AlexeiLevenkov: Thanks for your comment, but i just given for example – Ponmalar Jun 27 '13 at 05:54
  • 4
    How about `Directory.Exists(Path.GetPathRoot(pathGoesHere))`? – Alxandr Jun 27 '13 at 06:02
  • Great working fine but if path has only \\\\, it fails and it should show alert if the path has '/' – Ponmalar Jun 27 '13 at 07:00

8 Answers8

41
string drive = Path.GetPathRoot(FileLocation.Text);   // e.g. K:\

if (!Directory.Exists(drive))
{
     MessageBox.Show("Drive " + drive + " not found or inaccessible", 
                     "Error", MessageBoxButton.OK);
     return;
}

Of course, additional sanity checks (does the path root have at least three characters, is the second one a colon) should be added, but this will be left as an exercise to the reader.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • 2
    [Path.GetPathRoot](http://msdn.microsoft.com/en-us/library/system.io.path.getpathroot.aspx) is better than substring... – Alexei Levenkov Jun 27 '13 at 06:07
  • Great working fine but if path has only \\\\, it fails and it should show alert if the path has '/' – Ponmalar Jun 27 '13 at 07:01
  • 2
    @Ponmalar: `\\\\ ` is not a drive, so it *should* fail. Note that [GetPathRoot does work for UNC paths](http://stackoverflow.com/q/4230112/87698)! – Heinzi Jun 27 '13 at 07:03
  • Perfect. I was looking for a solution to check if a drive is un-formatted (inaccessible, like an encrypted TrueCrypt/VeraCrypt partition appears to windows). This does the job. – BananaAcid May 15 '17 at 02:58
  • That is not 100% correct: if you insert a USB drive get its DriveInfo, eject it , insert another USB Drive your Method will return true for the DriveIndo of the first, because Windows will mount both under the same letter, it would be sager to check the Drive Name too. – Tobias Brohl Mar 26 '18 at 09:05
  • 2
    Unfortunately, this method does not work for drives that exist but have no media in them (e.g. CD-ROM drives with no CD in them). I.e. the method shows the drive as inaccessible, but doesn't let one determine whether the drive letter is available or occupied (drive "exists"). – Eugene Mayevski 'Callback Oct 15 '19 at 08:14
8

you can do follow

bool isDriveExists(string driveLetterWithColonAndSlash)
{
    return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
}
Roman Pushkin
  • 5,639
  • 3
  • 40
  • 58
DreamChild
  • 411
  • 2
  • 3
2

This is Because Environment.SystemDirectory.XXXXX is all about where the system/windows is installed ...... not for whole HD.

for this you can use.....

    foreach (var item in System.IO.DriveInfo.GetDrives())
    {
        MessageBox.Show(item.ToString());
    }

it will show all drives including USBs that are attached.....

Shujaat Abdi
  • 556
  • 1
  • 5
  • 11
2

You can use Environment.GetLogicalDrives() to obtain an string[] of logical drives in your system.

var drive = Path.GetPathRoot(FileLocation.Text);
if (Environment.GetLogicalDrives().Contains(drive, StringComparer.InvariantCultureIgnoreCase))
{
         MessageBox.Show("Invalid Directory", "Error", MessageBoxButton.OK);
         return;
}
Pedro
  • 2,300
  • 1
  • 18
  • 22
1

you can try this....

MessageBox.Show(Environment.SystemDirectory.Contains("D").ToString());
Shujaat Abdi
  • 556
  • 1
  • 5
  • 11
  • 2
    This is obviously wrong - drive comparison should be case insensitive (hence must use `IndexOf` with comparison type instead of `Contains`) and better check for "drive letter" + ":" to avoid cases where letter happened to be part of the path. – Alexei Levenkov Jun 27 '13 at 06:04
1

I suppose this depends on what exactly you are hoping to accomplish. If you are trying to iterate through the drives and test to make sure each drive exists, then Environment.GetLogicalDrives() or DriveInfo.GetDrives() is appropriate as it allows you to iterate through the drives.

However, if all you care about is testing to see if ONE drive exists for a particular path, getting the entire list of drives to check if it is contained is a bit backwards. You would want to use Directory.Exists() as it just checks if that single path exists.

bool DriveExists(string fileLocation) {
    string drive = Path.GetPathRoot(fileLocation); // To ensure we are just testing the root directory.

    return Directory.Exists(drive); // Does the path exist?
}
Bryan
  • 2,870
  • 24
  • 39
  • 44
1

This will get if any drives' letter is E. You can change it to any other letter.

DriveInfo.GetDrives().Any(d => d.Name.ToUpper()[0] == 'E');
mekb
  • 554
  • 8
  • 22
0

You can check drives in C# like this

   foreach (var drive in DriveInfo.GetDrives())
   {
       //Code goes here
   }
WhileTrueSleep
  • 1,524
  • 1
  • 19
  • 32
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83