Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Drive Exists(string path)

Tags:

c#

wpf

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"
like image 877
Ponmalar Avatar asked Jun 27 '13 05:06

Ponmalar


2 Answers

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.

like image 155
Heinzi Avatar answered Oct 15 '22 12:10

Heinzi


you can do follow

bool isDriveExists(string driveLetterWithColonAndSlash)
{
    return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
}
like image 44
DreamChild Avatar answered Oct 15 '22 12:10

DreamChild