我在用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();
}
}
如您所见,如果在写入文件时出现问题,文件流将关闭两次。我知道这是可行的,但我不认为这是最好的实现。
我想我可以把
finally
阻塞,关闭
try
布洛克,但我把这个贴在这里是因为你们是专家,我想听听专家的声音。
提前谢谢。