- Home /
The question is answered, right answer was accepted
Using Directory.GetParent to change drives?
My project has an implemented file browser that looks like this:
In order to go up a level in the file hierarchy, the 'Up' button calls a method that returns the parent of the current directory.
public void upDirectory(){
dir = Directory.GetParent(dir).FullName;
showFiles ();
}
The problem is that I want the file browser to be able to navigate through other drives on the computer (E:\, H:\, etc), but the Directory.GetParent method only navigates as high as the root of the C drive. Attempting to go further than this throws 'NullReferenceException: Object reference not set to an instance of an object'.
Is there any way to navigate to the level of files that contains the paths to all the drives on the computer? If not, how else could I change the currently browsed drive?
Answer by Bunny83 · Nov 19, 2016 at 02:09 PM
There is nothing like a "path" or "folder" that contains drives as drives are the highest point of a path / folder on windows systems. You have to use System.IO.DriveInfo.GetDrives() which gives you a list of DriveInfo instances which represent all drives available.
Keep in mind that you might want to filter the array based on the drive type and the drive state. Drives can be empty / not ready (in case of removable drives like floppy or CD drives) and they could be readonly (like CD drives). Just check what the DriveInfo class provides.
Keep in mind that other operating systems might not have the concept of "drive letters". However if you only develop for windows that's not a problem.