首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C#中自动删除临时文件?

如何在C#中自动删除临时文件?
EN

Stack Overflow用户
提问于 2008-12-30 20:20:18
回答 9查看 68.1K关注 0票数 65

如果我的应用程序关闭或崩溃,有什么好方法来确保删除临时文件?理想情况下,我希望获得一个临时文件,使用它,然后忘记它。

现在,我保留了一个临时文件列表,并使用在Application.ApplicationExit上触发的EventHandler删除它们。

有没有更好的方法?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2008-12-30 14:30:42

如果进程过早终止,则没有任何保证,但是,我使用"using“来完成此操作。

代码语言:javascript
复制
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被释放或垃圾回收时,该文件将被删除(如果可能)。显然,您可以根据自己的喜好来使用它,或者在某个集合中使用它。

票数 84
EN

Stack Overflow用户

发布于 2014-08-21 02:14:33

考虑使用FileOptions.DeleteOnClose标志:

代码语言:javascript
复制
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
票数 70
EN

Stack Overflow用户

发布于 2008-12-30 14:45:40

您可以P/Invoke CreateFile并传递FILE_FLAG_DELETE_ON_CLOSE标志。这将告诉Windows在关闭所有句柄后删除该文件。另请参阅:Win32 CreateFile docs

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/400140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档