我如何自动删除在C#中临时文件? [英] How do I automatically delete tempfiles in c#?
问题描述
结果
有什么保证,如果我的应用程序关闭或崩溃一个临时文件被删除的好办法?理想情况下,我想获得一个临时文件,使用它,然后忘掉它。
What are a good way to ensure that a tempfile is deleted if my application closes or crashes? Ideally I would like to obtain a tempfile, use it and then forget about it.
现在我把我的临时文件的列表,并与触发的事件处理程序删除Application.ApplicationExit。
Right now I keep a list of my tempfiles and delete them with an eventhandler that triggers on Application.ApplicationExit.
有没有更好的办法?
推荐答案
如果进程过早杀死任何保证,但是,我用使用
要做到这一点..
Nothing is guaranteed if the process is killed prematurely, however, I use "using
" to do this..
using System;
using System.IO;
sealed class TempFile : IDisposable
{
string path;
public TempFile() : this(System.IO.Path.GetTempFileName()) { }
public TempFile(string path)
{
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
this.path = path;
}
public string Path
{
get
{
if (path == null) throw new ObjectDisposedException(GetType().Name);
return path;
}
}
~TempFile() { Dispose(false); }
public void Dispose() { Dispose(true); }
private void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
}
if (path != null)
{
try { File.Delete(path); }
catch { } // best effort
path = null;
}
}
}
static class Program
{
static void Main()
{
string path;
using (var tmp = new TempFile())
{
path = tmp.Path;
Console.WriteLine(File.Exists(path));
}
Console.WriteLine(File.Exists(path));
}
}
现在当临时文件
被处置,或者垃圾收集被删除的文件(如果可能)。你可以明显地将此作为紧密范围,只要你喜欢,或在某处集合
Now when the TempFile
is disposed or garbage-collected the file is deleted (if possible). You could obviously use this as tightly-scoped as you like, or in a collection somewhere.
这篇关于我如何自动删除在C#中临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!