【发布时间】:2018-08-30 11:29:01
【问题描述】:
所以我有这个function 来检查我的File 是否仍在使用(以便在尝试复制和删除之前等待):
private static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
using (stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
}
catch (IOException)
{
// The file is unavailable because it is:
// 1. Still being written to.
// 2. Being processed by another thread.
// 3. Does not exist (has already been processed).
if (stream != null)
stream.Close();
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
所以这足以调用Close() 方法或者使用using 来确保file 在完成我的方法后关闭?
【问题讨论】:
-
是的,包装在 using 块中是个好主意:msdn
-
将 try-catch 包装到 ?
-
只有try块里面的代码,当抛出一些异常时会自动调用dispose,所以如果需要,文件会被关闭。
-
所有这些代码实际上都是无用的。它可以在创建 Stream 的那一刻“免费使用”,并在 Stream 释放它的那一刻锁定它
-
尝试真正的操作,如果失败则知道它已被锁定。您可能希望以指数级等待时间重试几次