29

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?

Ronnie Overby
  • 45,287
  • 73
  • 267
  • 346

5 Answers5

14

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 2
    `FILE_ATTRIBUTE_TEMPORARY` will not delete the file automatically either. That flag merely hints to the OS to try to cache the file in memory as much as possible and possibly forgo the physical medium. The flag you want is `FILE_FLAG_DELETE_ON_CLOSE`. – Jesse C. Slicer Feb 08 '12 at 21:43
  • @JesseC.Slicer You are right, brain freeze on my part. I've now corrected. Thanks. – David Heffernan Feb 08 '12 at 21:47
  • No problem, sir! +1 for the info. – Jesse C. Slicer Feb 08 '12 at 22:46
  • No need to use P/Invoke for this, use the [FileStream constructor](https://msdn.microsoft.com/en-us/library/ms143396(v=vs.110).aspx) that takes in a [FileOptions](https://msdn.microsoft.com/en-us/library/system.io.fileoptions(v=vs.110).aspx) and pass in a `FileOptions.DeleteOnClose`. – Scott Chamberlain Sep 13 '17 at 02:12
6

For my Windows Forms & WPF apps, I added an event to delete the file when the app is closed. Like this:

private string GetTempFile() {
    string tmpfile = Path.GetTempFileName();
    this.Closed += (object sender, EventArgs e) => {
        if (File.Exists(tmpfile))
            File.Delete(tmpfile);
    };
    return tmpfile;
}
Rodger Vance
  • 171
  • 2
  • 3
6

No. It will not. This is why http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx specifically states

"The GetTempFileName method will raise an IOException if no unique temporary file name is available. To resolve this error, delete all unneeded temporary files."

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
arunpereira
  • 582
  • 5
  • 13
3

The answer to the question is no, and you'll probably never notice until you reach tmpFFFF.tmp and get an error. If this is on a webserver your operation is going to fail.

The path name used for temp files depends on the context. So if you're getting this error and it is an emergency condition you'll want to make sure you can quickly find correct tmp folder.

Running as a console app on Windows 8 gives me a path in my local prpofile:

C:\Users\sweaver\AppData\Local\Temp\2\tmp4193.tmp

And in IIS with Load User Profile = True for the AppPool I get :

C:\Users\APPPOOL_NAME\AppData\Local\Temp

And when Load User Profile = False I get a more manageable :

C:\Windows\TEMP\tmp7C32.tmp

You want to clean your temp files right away to avoid this!

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • Watch out if you create a tmp file and immediately delete it. Sometimes virus protection software will jump in and try to scan it and then prevent you from deleting it. – Simon_Weaver Sep 13 '17 at 00:55
1

This method worked well for me. Track when the opening program closes and then attempt to delete the file.

//Open it now and cleanup when program closes
Process p = Process.Start(path);
p.EnableRaisingEvents = true;
p.Exited += (sender, e) =>
{
    try
    {
        File.Delete(path);
    }
    catch { } //Suppress errors
};
jocull
  • 20,008
  • 22
  • 105
  • 149