gpt4 book ai didi

C# 关闭流并在失败时删除文件

转载 作者:行者123 更新时间:2023-11-30 13:28:44 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com