代码之家  ›  专栏  ›  技术社区  ›  Daniel Peñalba

C#关闭流并在出现故障时删除文件

  •  3
  • Daniel Peñalba  · 技术社区  · 14 年前

    我在用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 布洛克,但我把这个贴在这里是因为你们是专家,我想听听专家的声音。

    提前谢谢。

    1 回复  |  直到 14 年前
        1
  •  12
  •   BBoy    14 年前

    如果将文件流放在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; 
    }