I have a GUI (lxn/walk) app patcher that downloads a file via ftp, streams it to a temporary file and extracts the contents to update the local files. The remove file command is deferred.
This works unless the user exits the program while the file is downloading, then the file isn’t deleted.
I tried to fix this by doing a graceful exit by catching the signal and removing the file there. But unfortunately it throws an error that the file can’t be deleted because it is being used by another program. Which makes sense because the another program is actually itself still writing to the temporary file.
Now I’m stuck and don’t know what to do to make sure that the temporary file is automatically gone once the patcher is not running. How do I do that correctly?
The file could also be created as a normal file, not just a temp file. I would just like to ask too, where in windows is best to write a temporary file?
Now I’m stuck and don’t know what to do to make sure that the temporary file is automatically gone once the patcher is not running. How do I do that correctly?
There are no guaranteed ways to accomplish this as many things beyond the control of the application can cause it to exit. A power failure or kernel panic due to some hardware issue can crash the machine or force it to be restarted.
A strategy that is in common use is to implement a check on program startup for the status of the previous run. Some applications create a lock file at start and remove it on graceful exit. If this lock file exists when the program is restarted, this means the previous run did not result in a clean exit, and the application can take any corrective action. The exact action to be taken depends on the nature of the application, some refuse to start, others give warnings to users.
I would just like to ask too, where in windows is best to write a temporary file?
Each OS has its own location for temporary files. If you eliminate the dir
argument to TempFile
, it will create it in the appropriate location, as mentioned in the documentation:
TempFile
creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting*os.File
. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a"*"
, the random string replaces the last"*"
. If dir is the empty string,TempFile
uses the default directory for temporary files (seeos.TempDir
). Multiple programs callingTempFile
simultaneously will not choose the same file. The caller can usef.Name()
to find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed.
From os.TempDir
we see the following:
On Unix systems, it returns
$TMPDIR
if non-empty, else/tmp
. On Windows, it usesGetTempPath
, returning the first non-empty value from%TMP%
,%TEMP%
,%USERPROFILE%
, or the Windows directory. On Plan 9, it returns/tmp
.The directory is neither guaranteed to exist nor have accessible permissions.