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"
                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.
you can do follow
bool isDriveExists(string driveLetterWithColonAndSlash)
{
    return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With