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. :-)
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With