如果我的应用程序关闭或崩溃,有什么好方法来确保删除临时文件?理想情况下,我希望获得一个临时文件,使用它,然后忘记它。
现在,我保留了一个临时文件列表,并使用在Application.ApplicationExit上触发的EventHandler删除它们。
有没有更好的方法?
发布于 2008-12-30 14:30:42
如果进程过早终止,则没有任何保证,但是,我使用"using
“来完成此操作。
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
被释放或垃圾回收时,该文件将被删除(如果可能)。显然,您可以根据自己的喜好来使用它,或者在某个集合中使用它。
发布于 2014-08-21 02:14:33
考虑使用FileOptions.DeleteOnClose标志:
using (FileStream fs = new FileStream(Path.GetTempFileName(),
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None,
4096, FileOptions.RandomAccess | FileOptions.DeleteOnClose))
{
// temp file exists
}
// temp file is gone
发布于 2008-12-30 14:45:40
您可以P/Invoke CreateFile
并传递FILE_FLAG_DELETE_ON_CLOSE
标志。这将告诉Windows在关闭所有句柄后删除该文件。另请参阅:Win32 CreateFile
docs。
https://stackoverflow.com/questions/400140
复制相似问题