I've written some code that is supposed to write a file to the temp directory, then copy it to a permanent location, but find that doing so creates a permission-related error on the copy command. The code looks like this:
string tempPath = Path.GetTempFileName();
Stream theStream = new FileStream(tempPath, FileMode.Create);
// Do stuff.
File.Copy(tempPath, _CMan.SavePath, true);
File.Delete(tempPath);
I dimly remember that there's an API call I can make to create a temp file in a specified directory, passed as a parameter. But, that's a dim memory from my VB 6 days.
So, how do I create a temp file in a directory other than the temp directory defined by Windows?
Use mktemp -d . It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.
To permanently set the temporary directory for a Windows user account, go to Control Panel->System->Advanced, and enter the "Environment Variables" dialog window to find and change the TEMP and TMP variable settings in the "User variables".
Path.Combine(directoryYouWantTheRandomFile, Path.GetRandomFileName())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With