LoginSignup
6
6

More than 5 years have passed since last update.

存在しないファイルでもFile.Existsがtrueを返すことがある

Last updated at Posted at 2018-04-06

現象

File.Exists()を使って、リモートフォルダの削除済みファイルに対して存在チェックを行ったら存在すると言われてしまった。

環境

OS: Windows 7
.NET Framework: Ver 4
IDE: Visual Studio 2010

対策

ファイルが存在するかどうかの判断にFile.OpenRead()を使用するようにした。


bool FileExists(string filePath)
{
    if (File.Exists(filePath) == false)
    {
        return false;
    }

    // File.Exists()で存在するとなっても、実際は存在しないことがあるので再チェック
    try
    {
        using (FileStream fs = File.OpenRead(filePath)) { }
        return true;
    }
    catch (FileNotFoundException ex)
    {
        return false;
    }
}

追記(2018/11/02)

同僚から情報をもらったところ、どうやらSMB2.0のキャッシュ機能が原因みたいです。
https://support.microsoft.com/ja-jp/help/3040578

6
6
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
6
6