我正在使用 C# 处理文件流。它是一个存储缓存,所以如果写入文件时出现问题(损坏的数据,......),我需要删除文件并重新抛出异常以报告问题.我正在考虑如何以最佳方式实现它。我的第一次尝试是:
Stream fileStream = null;
try
{
fileStream = new FileStream(GetStorageFile(),
FileMode.Create, FileAccess.Write, FileShare.Write);
//write the file ...
}
catch (Exception ex)
{
//Close the stream first
if (fileStream != null)
{
fileStream.Close();
}
//Delete the file
File.Delete(GetStorageFile());
//Re-throw exception
throw;
}
finally
{
//Close stream for the normal case
if (fileStream != null)
{
fileStream.Close();
}
}
正如您将看到的,如果在写入文件时出现问题,fileStream 将被关闭两次。我知道它有效,但我认为这不是最好的实现方式。
我认为我可以删除 finally
block ,并关闭 try
block 中的流,但我已将其发布在这里,因为你们是专家,我想聆听专家的声音。
最佳答案
如果将 fileStream 放在 using block 中,则无需担心关闭它,然后只需进行清理(删除 catch block 中的文件)即可。
try
{
using (FileStream fileStream = new FileStream(GetStorageFile(),
FileMode.Create, FileAccess.Write, FileShare.Write))
{
//write the file ...
}
}
catch (Exception ex)
{
File.Delete(GetStorageFile());
//Re-throw exception
throw;
}
关于C# 关闭流并在失败时删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4264184/