Search code examples
c#wpftemp

The temporary folder is cleaned automatically?


I write temporary files to a temporary folder like this:

string path = Path.GetTempPath() + "\\" + Path.GetFileName(originalFilePath);
File.WriteAllBytes(path, data);

I write large files of images. So, I have a question - a temporary folder is cleaned itself over time? Or do I need to when the application exit delete all temporary files?

PS: Sorry for my English.


Solution

  • It is good practice to clean your temporary file at application exit. Create a class that manage temporary resources and use destructor to delete the temporary file(s).

    public class TemporaryFile
    {
        private string _fileName = String.Empty;
    
        <other stuffs...>
    
        ~TemporaryFile()
        {
            try
            {
                File.Delete(_fileName);
            }
            catch
            {
            }
        }
    }