Deleting Temporary Files after usage

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


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.

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.


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.