Deleting Temporary Files after usage

Matthias Meid picture Matthias Meid · Mar 18, 2009 · Viewed 12.1k times · Source

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

Any help is appreciated.

Matthias

Answer

Dirk Vollmar picture Dirk Vollmar · Mar 18, 2009

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