我需要验证特定文件是否打开,以防止复制该文件。
我尝试了很多示例,但都没有成功!例如,我尝试了这个:
protected virtual bool IsFileLocked(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();
}
//file is not locked
return false;
}
我需要指导...我哪里做错了?有什么建议吗?
stream
变量,要么在代码中的其他地方声明,但没有将原始创建的new
实例包装在using(){}
子句中。搜索所有使用stream
的地方,并确保你Dispose()、Close()、Flush()和Close流
,也可能是file.Open()
方法需要是FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
。 - MethodManusing (var stream = file.Open(...)) { ... }
。 - Austin Salonen