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

标签 c# filestream

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

相关文章:

c# - 为什么 Unity 会在此处抛出错误 CS0136 而 Visual Studio 2019 不会?

c# - 如何使用runco​​mmand在mongodb上搜索

c# - 在内存中创建并写入文本文件并一次性转换为字节数组

c# - 文件流.ReadByte : Byte's are never negative numbers?

sql-server - 使用 Windows 加密文件系统 (EFS) 在 FILESTREAMS 上进行 SQL Server 2012 全文搜索

c# - 使用流添加到 azure blob 存储

c# - 如果 C# 句子中存在该单词,如何屏蔽句子中的特定单词

c# - 通过反射实现接口(interface)

c# - 哈希表的通用版本是什么?

c# - C#中的部分文件读取