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

9
给定一个可能的完整文件路径,我将以 C:\dir\otherDir\possiblefile 为例。我想知道找出以下内容的好方法: C:\dir\otherDir\possiblefile 文件
C:\dir\otherDir 目录
是否存在。我不想创建文件夹,但如果文件不存在,我想创建该文件。该文件可能有扩展名,也可能没有。我想实现类似于下面这样的操作: enter image description here 我想出了一个解决方案,但在我看来有点过度设计。应该有一种简单的方法来完成它。
以下是我的代码:
// 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;
}

有什么建议吗?
1个回答

14

第三步和第四步可以被替换为:

if (Directory.Exists(Path.GetDirectoryName(filename)))
{
    return true;
}

这不仅更短,而且会返回包含Path.AltDirectorySeparatorChar(例如C:/dir/otherDir)的路径的正确值。


现在,这绝对更短,省去了手动解析并处理了替代分隔符。正是我一直在寻找的! - Joel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接