给定可能的完整文件路径,检查文件或父目录是否存在

Joe*_*oel 7 .net c# file-io path filepath

给定一个可能的完整文件路径,我将使用C:\ dir\otherDir\possiblefile的例子我想知道一个很好的方法来找出是否

C:\ dir\otherDir\possiblefile文件

C:\ dir\otherDir目录

存在.我不想创建文件夹,但我想创建该文件,如果它不存在.该文件可能有扩展名.我想完成这样的事情:

在此输入图像描述

我提出了一个解决方案,但在我看来,它有点矫枉过正.应该有一种简单的方法.

这是我的代码:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Doc*_*Max 12

您的步骤3和4可以替换为:

if (Directory.Exists(Path.GetDirectoryName(filename)))
{
    return true;
}
Run Code Online (Sandbox Code Playgroud)

这不仅会更短,而且会为包含Path.AltDirectorySeparatorChar此类的路径返回正确的值C:/dir/otherDir.