【问题标题】:Check if file or parent directory exist given a possible full file path在给定可能的完整文件路径的情况下检查文件或父目录是否存在
【发布时间】:2013-01-29 09:09:51
【问题描述】:

给定一个可能的完整文件路径,我将以 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;
}

有什么建议吗?

【问题讨论】:

    标签: c# .net file-io path filepath


    【解决方案1】:

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

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

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

    【讨论】:

    • 现在,这肯定更短,让我免于手动解析并处理替代分隔符。正是我一直在寻找的!
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多