可能性のある完全なファイル パスを指定して、 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;
}
助言がありますか?