【发布时间】:2018-05-11 15:08:16
【问题描述】:
我有以下方法来删除具有提供路径的文件
private void DestroyFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
if (File.Exists(path))
{
throw new IOException(string.Format("Failed to delete file: '{0}'.", path));
}
}
catch (Exception ex)
{
throw ex;
}
}
如果文件在 File.Delete 方法之后存在,我将得到抛出的 IOException。具体
System.IO.IOException):无法删除文件:'C:\Windows\TEMP\[FILE NAME]'。
我也确认执行完成后路径变量中的位置不存在该文件。我想知道在 File.Delete 之后文件系统更新和使用 File.Exists 再次检查之间是否存在竞争条件。有没有更好的方法可以顺利删除?我知道如果文件不存在, File.Delete 不会返回错误,所以这些检查可能有点多余。我应该检查文件是否正在使用而不是它是否存在?
一些重要的附加信息: 该程序可以并且确实经常成功运行,但最近经常出现此特定错误。
【问题讨论】:
-
此声明...
I have also confirmed that the file does not exist at the location in the path variable after the execution is complete....与这种可能性相矛盾...I am wondering if I am running up against a race condition between the file system updating after File.Delete and checking against it again with File.Exists.我强烈怀疑在您致电Delete()后有什么东西正在创建文件。跨度> -
我认为
C:\Windows是一个锁定目录。应用程序必须是管理员才能删除。此外,由于它位于 Windows 目录中,因此可能有某些东西正在使用该文件。 -
@Greg 我查看了权限,我可以排除它。该方法在某些时候确实有效,这可能是一个重要的细节
-
@JᴀʏMᴇᴇ 澄清一下,我的意思是,在 File.Delete 之后缓存可能没有完全更新,因此当 File.Exists 检查通过时,文件仍然以某种容量存在。我正在使用 GetTempFileName() 方法来创建临时文件,尽管没有传递任何参数。我想知道这是否会导致重复使用文件名,从而导致您提出的问题。