Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file or parent directory exist given a possible full file path

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:

enter image description here

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?

like image 328
Joel Avatar asked Feb 13 '13 18:02

Joel


People also ask

What method of file is used to test if a file or directory exists?

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.


1 Answers

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.

like image 169
DocMax Avatar answered Oct 18 '22 02:10

DocMax