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:

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?
Joel
source share