【问题标题】:C# close stream and delete file if something failed如果失败,C# 关闭流并删除文件
【发布时间】: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


    【解决方案1】:

    如果您将 fileStream 放在 using 块中,则无需担心关闭它,然后只需进行清理(删除 catch 块中的文件。

    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; 
    } 
    

    【讨论】:

      【解决方案2】:

      我相信你想要的是这样的:

      var fs = new FileStream(result.FilePath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
      

      我已将它与 ASP.Net 一起使用,让 Web 服务器将结果返回到磁盘上的临时文件,但要确保它在 Web 服务器完成后被清理 将其提供给客户。

      public static IActionResult TempFile(string tempPath, string mimeType, string fileDownloadName)
              {
                  var fs = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
                  var actionResult = new FileStreamResult(fileStream: fs, contentType: mimeType)
                  {
                      FileDownloadName = fileDownloadName
                  };
      
                  return actionResult;
              }
      

      【讨论】:

        猜你喜欢
        • 2011-04-21
        • 1970-01-01
        • 2013-06-07
        • 1970-01-01
        • 1970-01-01
        • 2015-03-04
        • 1970-01-01
        • 2014-06-03
        • 2020-10-22
        相关资源
        最近更新 更多