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



Question:

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.


Solution:1

use

Path.GetTempPath();  

or

Path.GetTempFileName();  

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


Solution:2

The others beat me to it regarding

System.IO.Path.GetTempPath()  

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  


Solution:3

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.


Solution:4

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


Solution:5

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
Previous
Next Post »