2013-02-13 184 views
7

鉴于可能的完整文件路径,我将以为例C:\ dir \ otherDir \ possiblefile我想知道寻找一个好方法出是否检查文件或父目录是否存在给定可能的完整文件路径

C:\目录\ otherDir \ possiblefile文件

C:\目录\ 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; 
} 

有什么建议?

回答

11

你的步骤3和4可以被代替:

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

即不仅短,但将返回正确的值用于包含Path.AltDirectorySeparatorCharC:/dir/otherDir路径。

+0

是的,除此之外,它是相当不错的去。 – 2013-02-13 18:12:04

+0

现在,这绝对是更短,从手动分析和处理替代分隔符。正是我一直在寻找的! – Joel 2013-02-14 11:06:52

相关问题