简体   繁体   中英

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:

在此输入图像描述

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM