Why would one ever use the %TEMP% folder now that Storage Sense can clean it at any time?

2.4k views Asked by At

Starting with Windows 10, Storage Sense has allowed users to specify %TEMP% folder cleanup that are as frequent as once a day. Technically it can run even more often is set to activate on low disk space, depending on one's disk usage patterns.

In light of that, what is the point of the %TEMP% folder? How would I ever use a folder where every file I put there can technically be removed by the system the moment after I finish writing it?

Here is a real world scenario where this hit me (code simplified for brevity):

var ffmpegPath = Path.Combine(Path.GetTempPath(), "ffmpeg");
DownloadFfmpeg(path: ffmpegPath); 

foreach (var videoFile in videoFiles) { //suppose there are dozens of files to process
   DoSomeHeavyProcessing(ffmpegPath);   //suppose each file takes an hour to process
}

This worked great for the first few hours, but then at some arbitrary point in time the downloaded ffmpeg folder was deleted and all the subsequent files could not be processed. In fact, if I understand correctly, in theory even code like this could fail:

var path = Path.Combine(Path.GetTempPath(), "foo");
File.WriteAllText(path, "bar");
Console.WriteLine(File.ReadAllText(path));

Now, I know how to solve this - simply use %APPDATA%, %LOCALAPPDATA% or %PROGRAMDATA%. But that's the point - since the advent of Storage Sense, why would I ever use %TEMP% rather than the former folders?

1

There are 1 answers

3
derpirscher On

The %TEMP% folder is -- as the name suggests -- for temporary files, which are only needed for a (typically short) period of time and can be deleted afterwards. In an ideal world, every app writing to the temp folder would clean up afterwards and delete the temporary files it created, when they are not needed any longer. But that does not happen, thus %TEMP% folders tend to become huge.

You can easily prevent Storage Sense from deleting files you still need by acquiring a file lock on that files. As long as a file in the %TEMP% folder is in use, it won't be deleted. Once processing the file has completed, you can free the file lock, which means you won't need the file any more and it can be deleted in the next run of Storage Sense.

This has the advantage, that your app doesn't need to clean up the "mess" (i.e temporary files) anymore. Just have the app lock them as long as they are needed. After the lock is freed (or the app exits, which will also free the file locks), they will automatically get deleted by the system.