SebastianStehle
SebastianStehle

Reputation: 2459

Deleting temp files automatically (C#)

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:

  1. It is okay to delete the files on the next run of the application. My idea is to use one main folder in the temp paths and one folder inside where the name of the folder is equal to the process id of the current process. When I run the application the next time I check all folders and also check if there is a process with this id running. If not I delete the folder. The problem with this solution is, that it needs admin permissions to run Process.GetProcessById
  2. I create one folder per process and use a lock file. I keep a stream opened with DeleteOnClose equal to true. On the next run of the application, I check all folders and their lock files. If there is no lock file or I can delete it I also delete the folder.

Do you have any other ideas?


EDIT: Implemented solution #2, works like a charm.

Upvotes: 0

Views: 985

Answers (1)

slugster
slugster

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

Related Questions