Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Temporary Files after usage

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.

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?

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. :-)

like image 292
Matthias Meid Avatar asked Mar 18 '09 17:03

Matthias Meid


People also ask

Is it OK to delete temp files?

If you're running low on storage space, you should consider deleting the temp files. You can either delete some or all of the temp files. Deleting them will free up space that you can use for other files and data. Keep in mind that you may not be able to delete temp files while the respective program is still running.

Is it OK to delete temp files in Windows 10?

As we mentioned, deleting temp files is a good way to regain storage space, but it's also possible that deleting temp files can help improve your PC if it's running a bit slow. If that's your goal and deleting the temp files didn't help, try clearing your PC's cache.


2 Answers

In .NET you can use the TempFileCollection class 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).

like image 183
Dirk Vollmar Avatar answered Oct 15 '22 02:10

Dirk Vollmar


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.

like image 20
Justin R. Avatar answered Oct 15 '22 01:10

Justin R.