Reputation: 2459
I have a scenario where I download files from a storage to the temp folder. Then I call a framework to process the file and this framework needs the file during the lifetime of the application. When the applications exits I close all files but when the application crashs the file does not get deleted. There can be multiple instances of the application.
What is the best way to get these files deleted? I have 2 ideas:
Do you have any other ideas?
EDIT: Implemented solution #2, works like a charm.
Upvotes: 0
Views: 985
Reputation: 49974
There is no inbuilt way to delete temp files automatically. But you can achieve this on reboot with a simple call to the WinAPI function MoveFileEx specifying the flag value MOVEFILE_DELAY_UNTIL_REBOOT - your temp file will be gone next time you boot (if it still exists). Here are two examples of doing this from C#: 1, and 2.
Calling this function has the effect of putting an entry into HKLM\System\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations
key in the registry (you can enter that value directly but this is the preferred way to do it). If you do this before doing your work with the temp file, then delete the temp file when you're finished with it. If your process crashes then all files that have been worked with will already have an entry in the registry, if the files are already gone upon the next reboot then nothing happens (i.e. there is no error raised or anything).
Upvotes: 4