2013-02-13 8 views
7

完全なファイルパスが指定されている場合、の例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; 
} 

任意の提案ですか?

答えて

11

あなたの手順3と4がで置き換えることができますだけでなく、短い

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

が、C:/dir/otherDirなどPath.AltDirectorySeparatorCharを含むパスの正しい値を返します。

+0

それ以外は、かなり良いです。 –

+0

今、それは間違いなく短く、私は手作業による解析から逃れることができ、代替セパレータを扱うことができます。まさに私が探していたもの! – Joel

関連する問題