How to test if a file is fully copied in .NET

后端 未结 9 1264
小鲜肉
小鲜肉 2021-01-17 12:27

I am monitoring a folder for new files and need to process them. The problem is that occasionally file opening fails, because system has not finished copying it.

Wha

9条回答
  •  有刺的猬
    2021-01-17 12:27

    I think the only sure way to do this is by trying to open the file exclusively and catching a specific exception. I usually hate using exceptions for normal application logic, but I'm afraid for this scenario there's no other way (at least I haven't found one yet):

    public bool FileIsDone(string path)
    {
      try
      {
        using (File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None))
        {
        }
      }
      catch(UnauthorizedAccessException)
      {
        return false;
      }
    
      return true;
    }
    

提交回复
热议问题