我想使用一个临时目录,一旦应用程序停止,它将自动删除。
框架中是否存在这样的机制,还是我应该自己编程?
谢谢 !
没有内置的东西可以做到这一点。您可以在启动时创建文件夹并将文件锁定在其中以防止它被另一个进程删除,但我很确定就是这样。
如果在应用程序未运行时此文件夹根本不存在很重要,那么您将需要一个监视应用程序和文件夹状态的服务。这样,如果应用程序崩溃或计算机重新启动,您将(合理地)确定在这些情况下都无法访问该文件夹。当然,您会希望让您的服务在启动时自动启动。
据我所知,不存在目录的内置方法,但您可以通过创建一次性类和using
构造来轻松模仿这种行为,这样可以确保即使应用程序意外终止,文件夹也会被删除:
public class TempFolder : IDisposable
{
public string RootPath { get; private set; }
public TempFolder()
{
RootPath = Path.GetTempPath();
}
public void Dispose()
{
Directory.Delete(RootPath, true);
}
}
然后,在您的应用程序中:
公共静态类 MyApp {
public static void Main(string[] args)
{
using(var tempFolder = new TempFolder())
{
// Do my stuff using tempFolder.RootPath as base path to create new files
}
// temporal directory will be deleted when we reach here
// even if an exception is thrown! :)
}
}
请注意,这是一种简单的方法;注意临时目录中的锁定文件可能导致Directory.Delete
操作失败
此外,在某些情况下,Dispose
无法调用该方法:
StackOverflowException
和OutOfMemoryException
顺便说一句,我正在使用类似的方法来处理一些必须对文件进行操作的 NUnit 测试,并且到目前为止它运行良好。
您还应该记住,应用程序可能会以不寻常的方式退出。甚至可能关闭计算机。因此,当您重新启动程序时,该文件夹可能已经存在。
Windows API has support for files to be created such that when the last handle to the file is closed, the file is deleted. However, I'm not sure such exists for a directory. Look into System.IO.File.CreateFile();
and FileOptions.DeleteOnClose
for description. Also look into underlying Win32 API - perhaps you can adapt it to your needs.