【发布时间】:2023-04-10 18:25:02
【问题描述】:
有没有办法查看文件是否已经打开?
【问题讨论】:
-
请提供更多细节。已经被您的进程或其他进程打开?打开期间,还是仅以写访问权限打开?分享呢?等等。这个问题太模糊了。
有没有办法查看文件是否已经打开?
【问题讨论】:
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)。这将允许您将异常管理放置在专门负责的类中并使其可重用。您甚至可以应用进一步的逻辑,例如测试文件大小以查看文件是否正在写入等,以提供更详细的响应。它还可以让你的消费代码更加简洁。
【讨论】: