Do files created with Path.GetTempFileName get cleaned up automatically?

Ronnie Overby picture Ronnie Overby · Feb 8, 2012 · Viewed 12.5k times · Source

I've always assumed the answer is yes, but now I'm trying to find the truth.

When I create a temp file using Path.GetTempFileName(), will windows automatically clean that up later?

What about if I create a directory under Path.GetTempPath()? Will windows clean it up?

Or is it the developer's responsibility to delete files created there?

Answer

David Heffernan picture David Heffernan · Feb 8, 2012

No they do not get deleted automatically. In order to create a file that will be deleted automatically when it is closed, pass FILE_FLAG_DELETE_ON_CLOSE to CreateFile.

The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles. If there are existing open handles to a file, the call fails unless they were all opened with the FILE_SHARE_DELETE share mode. Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified.

In order to gain access to this Win32 functionality from .net, use the SafeFileHandle class.