如何自动删除C#中的临时文件? [英] How do I automatically delete temp files in C#?
问题描述
在我的应用程序关闭或崩溃时,确保删除临时文件的一种好方法是什么?理想情况下,我想获取一个临时文件,使用它,然后再忽略它.
What's a good way to ensure that a temp file is deleted if my application closes or crashes? Ideally, I would like to obtain a temp file, use it, and then forget about it.
现在,我保留一个临时文件列表,并使用在Application.ApplicationExit上触发的EventHandler删除它们.
Right now, I keep a list of my temp files and delete them with an EventHandler that's triggered on Application.ApplicationExit.
有更好的方法吗?
推荐答案
如果过早地终止进程,则无法保证,但是,我使用" using
"来做到这一点.
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));
}
}
现在,当 TempFile
被处理或被垃圾收集时,该文件将被删除(如果可能).显然,您可以随意使用它,也可以在某个地方的集合中使用它.
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屋!