2010-11-24 116 views
1

我正在使用C#中的文件流。这是一个存储缓存,所以如果写入文件的某些东西坏了(损坏的数据,...),我需要删除文件重新抛出异常来报告问题。我正在考虑如何以最佳方式实施它。我的第一个学尝试是: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区块中的信息流,但我已在此发布此信息,因为您是专家,我希望听到专家的声音。

谢谢先进。

回答

10

如果你把FILESTREAM在使用块,你并不需要担心关闭它,然后就留在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; 
} 
+0

是啊,点,完美,谢谢! – 2010-11-24 07:15:22