Check if a file or parent directory exists with a possible full path to the file

Given the possible full path to the file, I will give an example with C: \ dir \ otherDir \ possible file . I would like to know about a good approach to figuring out if

C: \ dir \ otherDir \ possible file File

or C: \ dir \ otherDir Directory

exists. I do not want to create folders, but I want to create a file if it does not exist. A file can have an extension or not. I want to do something like this:

enter image description here

I came up with a solution, but, in my opinion, it went a little too far. There should be an easy way to do this.

Here is my code:

// Let example with C:\dir\otherDir\possiblefile private bool CheckFile(string filename) { // 1) check if file exists if (File.Exists(filename)) { // C:\dir\otherDir\possiblefile -> ok return true; } // 2) since the file may not have an extension, check for a directory if (Directory.Exists(filename)) { // possiblefile is a directory, not a file! //throw new Exception("A file was expected but a directory was found"); return false; } // 3) Go "up" in file tree // C:\dir\otherDir int separatorIndex = filename.LastIndexOf(Path.DirectorySeparatorChar); filename = filename.Substring(0, separatorIndex); // 4) Check if parent directory exists if (Directory.Exists(filename)) { // C:\dir\otherDir\ exists -> ok return true; } // C:\dir\otherDir not found //throw new Exception("Neither file not directory were found"); return false; } 

Any suggestions?

+7
source share
1 answer

Your steps 3 and 4 can be replaced by:

 if (Directory.Exists(Path.GetDirectoryName(filename))) { return true; } 

This is not only shorter, but will also return the correct value for paths containing Path.AltDirectorySeparatorChar , such as C:/dir/otherDir .

+11
source

All Articles