Tutorial :Correct location to save a temporary file in Windows?


I have a file I need to write to a temp location, what is the best place in Windows? This file needs to not move as I need to read it a couple of times and dispose it when I close the program.






As commentator pointed out, GetTempFileName() is not threadsafe - but you can construct unique file names based on GUIDs.


The others beat me to it regarding


But you can also look into application data folder. That will allow you more control over your file, like the ability have 1 shared for all users or 1 per user.

Application.CommonAppDataPath  Application.UserAppDataPath  


Use the Windows API function GetTempPath() from System.IO.Path (see MSDN)

using System.IO    ...    myTempPath = Path.GetTempPath();  

You should be aware that the filesystem might well change during your program's execution. Either the Temp path may change (unlikely, granted), or your temporary file might have been moved or deleted by the user.

Be prepared to check for its existence each time you access it and handle the case when it's not found gracefully.


If you need your application to write to a temporary location and work in partial trust, you'd need to look into IsolatedStorage.


If you want to build your own custom temporary filename in reference to a temporary location, I use something like this, to strip off the PATH and apply my own filename ...

string wsPDFfile = Path.GetTempPath() + wsStudentID + "_" + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".pdf";  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »