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:\\TestDriv
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.....
You can check drives in C# like this
foreach (var drive in DriveInfo.GetDrives())
{
//Code goes here
}
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?
}
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;
}
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);
}