应该使用Dispose()或Finalize()删除临时文件吗? [英] Should Dispose() or Finalize() be used to delete temporary files?
问题描述
我有一个在活动时使用临时文件(Path.GetTempFileName()
)的类.我要确保在关闭程序后这些文件不会保留在用户的硬盘上,不会占用空间.现在,我的课程有一个Close()
方法,该方法检查该课程使用的任何临时文件是否仍然存在并将其删除.
I have a class that makes use of temporary files (Path.GetTempFileName()
) while it is active. I want to make sure these files do not remain on the user's hard drive taking up space after my program is closed. Right now my class has a Close()
method which checks if any temporary files used by the class still exist and deletes them.
将这段代码放在Dispose()或Finalize()方法中会更有意义吗?
Would it make more sense to put this code in the Dispose() or Finalize() methods instead?
推荐答案
Better yet would be to create the file with FileOptions.DeleteOnClose
. This will ensure that the operating system forcibly deletes the file when your process exits (even in the case of a rude abort). Of course, you will still want to close/delete the file yourself when you are done with it, but this provides a nice backstop to ensure that you don't allow the files to be sit around forever
示例:
using (FileStream fs = File.Create(Path.GetTempFileName(), Int16.MaxValue,
FileOptions.DeleteOnClose))
{
// Use temp file
} // The file will be deleted here
这篇关于应该使用Dispose()或Finalize()删除临时文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!