zoukankan      html  css  js  c++  java
  • Wait until file is closed/unlocked http://blog.lukesw.net/2009/07/waituntilfileisclosed.html 武胜

    Wait until file is closed/unlocked

     

    Sometimes you want to wait until some specified file is available for reading/writing. For example, you wait until other process finishes packing into a zip file, or wait until some file is fully uploaded to the server so you can compress it at server side, or something like that. There are some solutions in which checking whether the file can be opened mainly looks like this:

    public static bool IsFileAvailable(string path)
    {
      try
      {
        if (!File.Exists(path)) return false;
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { };
        return true;
      }
      catch (Exception) { return false; }
    }

    There are some drawbacks to this approach. Imagine that this code returns true, but before we actually open the file, some other process or thread manages to open and lock the file. Besides, a generic exception should not be caught, because we might “eat” some really important exception like OutOfMemoryException or similar. A better solution would be to return obtained file stream, and catch only file-related exceptions.

    After some refactoring, adding extension methods, and adding ‘wait’ methods, the final code looks like this:

    C# Download TryOpenFile.cs file
    public static class FileExt
    {
      public static FileStream TryOpenFile(string path, FileAccess access, FileShare share)
      {
        try
        {
          if (!File.Exists(path)) return null;
          return File.Open(path, FileMode.Open, access, share);
        }
        catch (IOException) { return null; }
        catch (UnauthorizedAccessException) { return null; }
      }
    
      public static FileStream WaitAndOpenFile(string path, FileAccess access, FileShare share, TimeSpan timeout)
      {
        DateTime dt = DateTime.UtcNow;
        FileStream fs = null;
        while ((fs = TryOpenFile(path, access, share)) == null && (DateTime.UtcNow - dt) < timeout)
        {
          Thread.Sleep(250); // who knows better way and wants a free cookie? ;)
        }
        return fs;
      }
    
    #region " Other Methods"
      public static FileStream TryOpenFileForReading(this FileInfo fileInfo) { return TryOpenFileForReading(fileInfo.FullName); }
      public static FileStream TryOpenFileForReading(string path) { return TryOpenFile(path, FileAccess.Read); }
      public static FileStream TryOpenFileForWriting(this FileInfo fileInfo) { return TryOpenFileForWriting(fileInfo.FullName); }
      public static FileStream TryOpenFileForWriting(string path) { return TryOpenFile(path, FileAccess.ReadWrite); }
      public static FileStream TryOpenFile(this FileInfo fileInfo, FileAccess access) { return TryOpenFile(fileInfo.FullName, access); }
      public static FileStream TryOpenFile(string path, FileAccess access) { return TryOpenFile(path, access, FileShare.None); }
      public static FileStream TryOpenFile(this FileInfo fileInfo, FileAccess access, FileShare share) { return TryOpenFile(fileInfo.FullName, access, share); }
      public static FileStream WaitAndOpenFileForReading(this FileInfo fileInfo, TimeSpan timeout) { return WaitAndOpenFileForReading(fileInfo.FullName, timeout); }
      public static FileStream WaitAndOpenFileForReading(string path, TimeSpan timeout) { return WaitAndOpenFile(path, FileAccess.Read, timeout); }
      public static FileStream WaitAndOpenFileForWriting(this FileInfo fileInfo, TimeSpan timeout) { return WaitAndOpenFileForWriting(fileInfo.FullName, timeout); }
      public static FileStream WaitAndOpenFileForWriting(string path, TimeSpan timeout) { return WaitAndOpenFile(path, FileAccess.ReadWrite, timeout); }
      public static FileStream WaitAndOpenFile(this FileInfo fileInfo, FileAccess access, TimeSpan timeout) { return WaitAndOpenFile(fileInfo.FullName, access, timeout); }
      public static FileStream WaitAndOpenFile(string path, FileAccess access, TimeSpan timeout) { return WaitAndOpenFile(path, access, FileShare.None, timeout); }
      public static FileStream WaitAndOpenFile(this FileInfo fileInfo, FileAccess access, FileShare share, TimeSpan timeout) { return WaitAndOpenFile(fileInfo.FullName, access, share, timeout); }
    #endregion
    }

    This code also is not perfect. I known of no better method of waiting until a file is closed by the previous owner, except waiting in a loop. We can only make this method a little better by using the Thread.Sleep method which prevents CPU from being used all the time.

    There is one more thing. Why is the FileShare.None flag used by default? Only because we do not want other processes/threads to mess with our file which we obtained with such “difficulties”.

  • 相关阅读:
    企业库应用实践系列五:创建模板引擎Library
    关于HtmlHelper:是MVC自作聪明,还是我不够明白?
    企业库应用实践系列二:对象创建原理详解
    企业库应用实践系列三:自定义构造函数
    专业导论 计算机科学概论
    企业短期项目,缺人手
    光脚丫学LINQ(040):引发未将对象引用设置到对象的实例的异常
    光脚丫学LINQ(045):如何表示计算所得列(LINQ to SQL)
    光脚丫学LINQ(042):如何将列表示为由数据库生成的列
    光脚丫学LINQ(043):为实体类的列成员指定在数据库中的数据类型
  • 原文地址:https://www.cnblogs.com/zeroone/p/2988554.html
Copyright © 2011-2022 走看看