在调用File.Delete之前应该调用File.Exists吗? [英] Should I call File.Exists before calling File.Delete?

查看:195
本文介绍了在调用File.Delete之前应该调用File.Exists吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的finally子句中有一个 File.Delete ,如下所示:

  finally 
{
//删除临时文件
if(File.Exists(convertedFile))
File.Delete(convertedFile);
}

根据 C#文档,在不存在的文件上调用File.Delete不会抛出任何异常。



是否可以删除 File.Exists 包装,否则会让我可能发生额外的例外? / p>

解决方案

如果你需要它,这是不够的,因为文件可以在你确认它存在后被删除。在这种情况下,最好的做法是简单地尝试删除该文件。如果没有找到找不到文件类型的错误,那么您将知道该文件不存在。这将删除额外的操作,并避免任何种族的窗口。


I have a File.Delete in my finally clause like so:

finally
{
    //remove the temporary file
    if(File.Exists(transformedFile))
        File.Delete(transformedFile);
}

According to the C# documentation, calling File.Delete on a nonexistent file will not throw any exceptions.

Is it okay to remove the File.Exists wrapped, or will that expose me to possible additional exceptions?

解决方案

If you need it, it's insufficient, as the file could be deleted after you confirm that it exists. In a case like this, the best practice is to simply try to delete the file. If it fails with a "file not found" type of error, then you'll know the file didn't exist. This removes an extra operation and avoids any kind of race window.

这篇关于在调用File.Delete之前应该调用File.Exists吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆