检查文件是否打开

有没有办法find一个文件是否已经打开或没有?

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; } 

作为@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; } 

如果你的意思是你想检查一个文件是否打开,然后再尝试打开它,那么没有。 (至少不要低级别,并检查系统中打开的每个文件句柄。)

此外,当你得到它的信息将是旧的。 即使测试将返回文件未打开,它可能已经打开之前,有机会使用返回值。

所以,处理这种情况的正确方法是尝试打开文件,并处理可能发生的错误。

同意。 我将创建一个包装打开文件逻辑或至少测试(IsFileAvailable)的指定类。 这将允许您将异常管理与专门负责的类相关联,并使其可重用。 你甚至可以应用更多的逻辑,比如测试文件的大小,看看文件是否正在写入等,给出更详细的回应。 这也将使您的消费代码更清洁。