0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

フォルダの存在チェック

Posted at

はじめに

C#でWebアプリを構築しています。
そこで、フォルダの存在チェックをしようと思います。

フォルダの存在チェックといえば「Directory.Exists」ですね。

Directory.Existsを使う
if (Directory.Exists(path)) {
    // フォルダがある
} else {
    // フォルダがない
}

ローカル環境ではうまくいきましたが、Webサーバーにアップするとフォルダは存在するのにfalseが返却されました。

なぜだろう:thinking:

どうやら「Directory.Exists」は、フォルダの存在ではなくフォルダが参照できるかを確認するメソッドのようです。

つまり、参照権限がないとfalseが返却されます。
ローカル環境からは参照できるフォルダが、Webサーバーからは参照できなかったようです。

どうするか:thinking:

javascriptで何とかしてみたかったのですが、ダメでした。

フォルダがないのか、権限がないのか判別する術はないか…

調べたところ「Directory.GetFiles」が使えそうです。

こちらはフォルダ内のファイルが確認できないときにExceptionが発生します。
Exceptionをcatchすると、なぜファイルが確認できなかったか判別ができます。

Directory.GetFilesを使う
bool isDirectoryExists;
try
{
    Directory.GetFiles(path);
    
    // フォルダがある
    isDirectoryExists = true;
}
catch (ArgumentNullException)
{
    // パスがnull(フォルダがない)
    isDirectoryExists = false;
}
catch (ArgumentException)
{
    // パスに禁止文字あり(フォルダがない)
    isDirectoryExists = false;
}
catch (PathTooLongException)
{
    // パスが長い(フォルダはあるかもしれない)
    isDirectoryExists = true;
}
catch (DirectoryNotFoundException)
{
    // フォルダがない
    isDirectoryExists = false;
}
catch (UnauthorizedAccessException)
{
    // 権限がない(フォルダがある)
    isDirectoryExists = true;
}
catch (IOException)
{
    // その他(フォルダはあるかもしれない)
    isDirectoryExists = true;
}

if (isDirectoryExists) {
    // フォルダがある(かもしれない)
} else {
    // フォルダがない
}

これで「フォルダがないのか」「権限がないのか」を判別することができました。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?