Are files in the temporary folder automatically deleted?

Yaron Naveh picture Yaron Naveh · Feb 14, 2010 · Viewed 10.3k times · Source

If I create some file using Path.GetTempPath() - does it automatically get deleted at some stage, or is it up to me to delete it?

Answer

finnw picture finnw · Feb 14, 2010

FileOptions.DeleteOnClose will cause the file to be deleted automatically when closed. This also works if the program is terminated by an exception.

For example, as mentioned in this answer:

using (FileStream fs = new FileStream(Path.GetTempPath() + "foo.bar",
       FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None,
       4096, FileOptions.RandomAccess | FileOptions.DeleteOnClose))
{
    // temp file exists
}

// temp file is gone