检查文件是否已打开

Md.*_*din 17 c# windows io file-io

有没有办法找到文件是否已经打开?

Pra*_*ana 26

protected virtual bool IsFileinUse(FileInfo file)
{
     FileStream stream = null;

     try
     {
         stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
     }
     catch (IOException)
     {
         //the file is unavailable because it is:
         //still being written to
         //or being processed by another thread
         //or does not exist (has already been processed)
         return true;
     }
     finally
     {
         if (stream != null)
         stream.Close();
     }
     return false; 
}
Run Code Online (Sandbox Code Playgroud)

  • 令人惊讶的是,大多数语言都没有测试文件的方法是开放的.我们曾经在OS/2中的C++下使用相同类型的方法.即尝试打开文件独占.它运作得很好,但我从未想过它优雅. (4认同)
  • 这个答案与另一个问题的答案相同:(http://stackoverflow.com/a/937558/38657)...说,这是一个很好的答案. (3认同)
  • 如果进程没有对文件的写访问权,则会产生误导性结果(打开将失败,但不一定是因为句柄存在.)打开读取访问权限会更不容易出错. (2认同)
  • 它不是一种语言功能,它是一种操作系统功能.只是不存在用于查询该信息的简单API(在Windows中).它有可能获得,但它是低级别的,并且必须指定许多参数才能知道"打开"的含义. (2认同)

Mat*_*ott 7

作为@pranay rana,但我们需要确保关闭文件句柄:

public bool IsFileInUse(string path)
{
  if (string.IsNullOrEmpty(path))
    throw new ArgumentException("'path' cannot be null or empty.", "path");

  try {
    using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { }
  } catch (IOException) {
    return true;
  }

  return false;
}
Run Code Online (Sandbox Code Playgroud)