【发布时间】:2010-11-24 06:55:03
【问题描述】:
我正在使用 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 块,并关闭try 块中的流,但是我在这里发布了这个,因为你们是专家,我想听听专家的声音。
【问题讨论】:
标签: c# filestream