windows 使用后删除临时文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/659351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:10:22  来源:igfitidea点击:

Deleting Temporary Files after usage

.netwindowstemporary-files

提问by Matthias Meid

I need to work with some temporary files in my Windows Forms .NET 3.5 application. Those files are opened in an external application that can of course be running for a longer time than my own program.

我需要在我的 Windows Forms .NET 3.5 应用程序中处理一些临时文件。这些文件是在外部应用程序中打开的,该应用程序当然可以比我自己的程序运行更长的时间。

Are there any best practices to make sure these temporary files are cleaned up at any time in order to avoid filling the user's hard disk with "junk" files which aren't needed anymore? Or does even Windows kind of handle this automatically?

是否有任何最佳做法可以确保随时清理这些临时文件,以避免用户硬盘充满不再需要的“垃圾”文件?或者甚至 Windows 会自动处理这个?

A nice example is any mail client: When you open an attachment in any application, it is usually written to a temporary file which is opened. Is there a way to figure out how those files manage cleanup?

一个很好的例子是任何邮件客户端:当你在任何应用程序中打开一个附件时,它通常被写入一个打开的临时文件中。有没有办法弄清楚这些文件如何管理清理?

Using Google has shown me many, many cleanup and tune-up tools to clean the temp directory by hand, but I'd not like to force the users to do so. :-)

使用 Google 向我展示了许多清理和调整工具来手动清理临时目录,但我不想强迫用户这样做。:-)

Any help is appreciated.

任何帮助表示赞赏。

Matthias

马蒂亚斯

采纳答案by Ken Browning

If you attempt to deterministically clear the contents of a Temporary Files type folder, you risk removing files that are in use by other processes. The Windows operating system provides tools to allow users to remove those files when the volume's available disk space reaches a certain threshold.

如果您尝试确定性地清除临时文件类型文件夹的内容,则可能会删除其他进程正在使用的文件。Windows 操作系统提供了一些工具,允许用户在卷的可用磁盘空间达到特定阈值时删除这些文件。

Now, if you can determine that after you use a specific temporary file that it will no longer be needed, then there's no down-side to deleting that specific file.

现在,如果您可以确定在使用特定临时文件后不再需要它,那么删除该特定文件没有任何不利之处。

回答by Dirk Vollmar

In .NET you can use the TempFileCollectionclass for managing a set of temporary files to be cleaned up by your application (Note that it is rather hidden in the CodeDom namespace). Obviously you can't delete any files not owned by yourself, because the files might still be opened by another application (and deleting them might cause serious issues).

在 .NET 中,您可以使用TempFileCollection该类来管理一组要由您的应用程序清理的临时文件(请注意,它在 CodeDom 命名空间中相当隐藏)。显然你不能删除任何不属于你自己的文件,因为这些文件可能仍然被另一个应用程序打开(删除它们可能会导致严重的问题)。

回答by Justin R.

The responsibility for cleaning up temporary files ought to be on the application that created them. It is very easy. I use a class that looks something like this:

清理临时文件的责任应该由创建它们的应用程序负责。这很容易。我使用一个看起来像这样的类:

public class TempFile : IDisposable
{
    public TempFile()
    { this.path = System.IO.Path.GetTempFileName(); }

    public void Dispose()
    { File.Delete(path); }

    private string path;
    public string Path { get { return path; } }
}

If you are required to clean up another application's temporary files it needs some means of communicating with yours. At a minimum it should be able to provide a semaphore. However the complexity of doing this is greater than the complexity of just having the originating application take care of its own files.

如果您需要清理另一个应用程序的临时文件,它需要一些与您的通信方式。至少它应该能够提供一个信号量。然而,这样做的复杂性比仅仅让原始应用程序处理它自己的文件的复杂性要大。

回答by Rikalous

We have a similar file lifetime problem - the (winforms) application can fetch a document from a central repository store for the user to view, but the user should be able to close our app without it affecting the file they are viewing. Due to security concerns the document files need to be cleaned up so they aren't lying around too long.

我们有一个类似的文件生命周期问题——(winforms)应用程序可以从中央存储库中获取一个文档供用户查看,但用户应该能够关闭我们的应用程序而不会影响他们正在查看的文件。出于安全考虑,需要清理文档文件,以免它们闲置太久。

The solution we use is to create a folder with a date-derived name in the users' isolated storage area and use that as today's cache. At application close-down and start-up we check for previous dated cache folders and delete them (and contents).

我们使用的解决方案是在用户的独立存储区域中创建一个具有日期派生名称的文件夹,并将其用作今天的缓存。在应用程序关闭和启动时,我们检查以前过时的缓存文件夹并删除它们(和内容)。

回答by Dave

When using temporary files in ASP.NET, use the PAGE_DISPOSED event to delete any temporary files you created in the page. Otherwise you may end up with contention with components that do not let go until DISPOSED.

在 ASP.NET 中使用临时文件时,请使用 PAGE_DISPOSED 事件删除您在页面中创建的任何临时文件。否则,您最终可能会与在 DISPOSED 之前不会放开的组件发生争用。

回答by Scott Wisniewski

I believe they will be deleted when the user logs out.

我相信当用户注销时它们会被删除。

Back in the days when people turned off their pcs every day, that was probably a perfect solution.

回到人们每天关闭电脑的时代,这可能是一个完美的解决方案。

Now, people can potentially go months without logging off, so it may not be a good idea to rely on that.

现在,人们可能几个月都不会注销,因此依赖它可能不是一个好主意。

Also, if they turn their machine off without shutting down then the files won't get deleted either.

此外,如果他们在不关机的情况下关闭机器,则文件也不会被删除。

You could use a file system watcher that watches the file you write, and wait for some period of inactivity (10 minuites, 1 hour, 1 day, or what ever) and then delete the file.

您可以使用文件系统观察器来观察您编写的文件,并等待一段时间不活动(10 分钟、1 小时、1 天或其他时间),然后删除该文件。

That won't work for everything though. Some programs may have a file "open", but might not have the underlying file locked. If that happens, then you would have no way of knowing when it's safe to delete the file.

但这并不适用于所有情况。某些程序可能有一个“打开”的文件,但可能没有锁定底层文件。如果发生这种情况,您将无法知道何时可以安全地删除文件。

However, I'm thinking you can probably just ignore the problem. Most people probably have a surplus of hard drive space anyways, so they probably aren't likely to run into it. If they do, I think Windows pops up a low disk space dialog that gives them the option to clear their temp directory, which would solve the problem.

但是,我认为您可能可以忽略这个问题。无论如何,大多数人可能都有多余的硬盘空间,所以他们可能不太可能遇到它。如果他们这样做,我认为 Windows 会弹出一个磁盘空间不足的对话框,让他们可以选择清除临时目录,这将解决问题。

Update:

更新:

I think Windows Update will restart the user's computer about once a month, so the temp files should be cleared when that happens.

我认为 Windows 更新将大约每月重新启动一次用户的计算机,因此在发生这种情况时应该清除临时文件。

There's no guarantee that there won't be problems, but in practice I think it should be pretty rare.

不能保证不会有问题,但在实践中我认为它应该很少见。

Update 2:

更新 2:

Prompted by a comment, I went and actually tested this, and it looks like windows doesn't delete the temp files when the user logs out. However, I still say that in the OP's case, this isn't a real problem. When it becomes a problem (because disk space is low) Windows will prompt the user to delete temporary files.

在评论的提示下,我去实际测试了这个,看起来当用户注销时 Windows 不会删除临时文件。但是,我仍然说在 OP 的情况下,这不是真正的问题。当出现问题时(因为磁盘空间不足)Windows 会提示用户删除临时文件。

回答by Konard

I use this solution (quite reliable):

我使用这个解决方案(相当可靠):

using System.IO;
using System.Reflection;

namespace Konard.Helpers
{
    public static partial class TemporaryFiles
    {
        private const string UserFilesListFilenamePrefix = ".used-temporary-files.txt";
        static private readonly object UsedFilesListLock = new object();

        private static string GetUsedFilesListFilename()
        {
            return Assembly.GetEntryAssembly().Location + UserFilesListFilenamePrefix;
        }

        private static void AddToUsedFilesList(string filename)
        {
            lock (UsedFilesListLock)
            {
                using (var writer = File.AppendText(GetUsedFilesListFilename()))
                    writer.WriteLine(filename);
            }
        }

        public static string UseNew()
        {
            var filename = Path.GetTempFileName();
            AddToUsedFilesList(filename);
            return filename;
        }

        public static void DeleteAllPreviouslyUsed()
        {
            lock (UsedFilesListLock)
            {
                var usedFilesListFilename = GetUsedFilesListFilename();

                if (!File.Exists(usedFilesListFilename))
                    return;

                using (var listFile = File.Open(usedFilesListFilename, FileMode.Open))
                {
                    using (var reader = new StreamReader(listFile))
                    {
                        string tempFileToDelete;
                        while ((tempFileToDelete = reader.ReadLine()) != null)
                        {
                            if (File.Exists(tempFileToDelete))
                                File.Delete(tempFileToDelete);
                        }
                    }
                }

                // Clean up
                using (File.Open(usedFilesListFilename, FileMode.Truncate)) { }
            }
        }
    }
}

Every time you need temporary file use:

每次需要临时文件时使用:

var tempFile = TemporaryFiles.UseNew();

To be sure all temporary files are deleted after application closes or crashes put

确保在应用程序关闭或崩溃后删除所有临时文件

TemporaryFiles.DeleteAllPreviouslyUsed();

at start of the application.

在应用程序开始时。

回答by Mutant

  • you can create one temp file, in which you can keep writing the file names created during the process, at the end of processing may be you can (precondition - Implement IDisposable and) delete in the Disponse method after operation is completed.

  • Other way is write independent process which perform cleanup every interval.

  • Attache the date at the end of the file, and delete at the end of the day with that date, and process will generate new files wiht new date at the end.

  • one good suggestion given by divo tempfilecollection class.

  • 可以创建一个临时文件,在里面可以继续写入处理过程中创建的文件名,处理结束时可以在操作完成后(前提-实现IDisposable和)在Disponse方法中删除。

  • 另一种方法是写独立进程,它在每个间隔执行清理。

  • 在文件末尾附加日期,并在该日期的末尾删除,进程将生成末尾带有新日期的新文件。

  • div tempfilecollection 类给出了一个很好的建议。

hope it helps.

希望能帮助到你。