Tea*_*ild 5 c# file-io exception-handling
MSDN告诉我们,当你调用"File.Delete(path);"时 在不存在的文件上生成异常.
在执行删除之前调用delete方法并使用try/catch块来避免错误或验证文件的存在会更有效吗?
我倾向于认为避免try/catch块更好.当您知道如何检查错误时,为什么会发生错误.
无论如何,这里是一些示例代码:
// Option 1: Just delete the file and ignore any exceptions
/// <summary>
/// Remove the files from the local server if the DeleteAfterTransfer flag has been set
/// </summary>
/// <param name="FilesToSend">a list of full file paths to be removed from the local server</param>
private void RemoveLocalFiles(List<string> LocalFiles)
{
// Ensure there is something to process
if (LocalFiles != null && LocalFiles.Count > 0 && m_DeleteAfterTransfer == true)
{
foreach (string file in LocalFiles)
{
try { File.Delete(file); }
catch { }
}
}
}
// Option 2: Check for the existence of the file before delting
private void RemoveLocalFiles(List<string> LocalFiles )
{
// Ensure there is something to process
if (LocalFiles != null && LocalFiles.Count > 0 && m_DeleteAfterTransfer == true)
{
foreach (string file in LocalFiles)
{
if( File.Exists( file ) == true)
File.Delete(file);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试实现的一些背景:代码是FTP包装器类的一部分,它将FTP功能的功能简化为仅需要的功能,并且可以通过单个方法调用来调用.在这种情况下,我们有一个名为"DeleteAfterTransfer"的标志,如果设置为true将完成该工作.如果文件首先不存在,我希望在达到这一点之前有一个例外.我想我在这里回答了我自己的问题,但检查文件的存在并不比验证我有权执行任务或任何其他潜在错误更重要.
您基本上有三个选项,考虑到当您的文件不存在时File.Delete 不会抛出异常:
使用File.Exists,每次需要额外的往返磁盘(归功于Alexandre C),再加上File.Delete到磁盘的往返.这很慢.但是如果你想在文件不存在时做一些特定的事情,这是唯一的方法.
使用异常处理.考虑到进入try/catch块相对较快(我认为大约4-6 m-ops),开销可以忽略不计,您可以选择捕获特定的异常,比如IOException文件正在使用时.这可能非常有用,但是当文件不存在时你将无法行动,因为它不会抛出.注意:这是避免竞争条件的最简单方法,正如Alexandre C在下面更详细地解释的那样.
使用异常处理和 File.Exists.这可能是最慢的,但只是稍微如此,并且当文件不存在时,唯一的方法是捕获异常并执行特定的操作(发出警告?).
我原始答案的摘要,给出了一些关于使用和处理异常的更一般的建议:
Exception).