Given a possible full file path, I'll example with C:\dir\otherDir\possiblefile I'd like to know of a good approach to finding out whether
C:\dir\otherDir\possiblefile File
or C:\dir\otherDir Directory
exist. I don't want to create folders, but I want to create the file if it does not exists. The file may have an extension or not. I want to accomplish something like this:
I came up with a solution, but it is a little bit overkill, in my opinion. There should be a simple way of doing it.
Here's my code:
// Let's 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?
File. exists() is used to check whether a file or a directory exists or not. This method returns true if the file or directory specified by the abstract path name exists and false if it does not exist.
Your steps 3 and 4 can be replaced by:
if (Directory.Exists(Path.GetDirectoryName(filename)))
{
return true;
}
That is not only shorter, but will return the right value for paths containing Path.AltDirectorySeparatorChar
such as C:/dir/otherDir
.
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