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

て烟熏妆下的殇ゞ 提交于 2019-12-03 05:38:04

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.

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

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;
}

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!

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
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!