Reputation: 999
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.
Upvotes: 47
Views: 15010
Reputation: 4838
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";
Upvotes: 0
Reputation: 5623
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
Upvotes: 11
Reputation: 25640
If you need your application to write to a temporary location and work in partial trust, you'd need to look into IsolatedStorage.
Upvotes: 0
Reputation: 53934
use
Path.GetTempPath();
or
Path.GetTempFileName();
As commentator pointed out, GetTempFileName() is not threadsafe - but you can construct unique file names based on GUIDs.
Upvotes: 43
Reputation: 10064
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.
Upvotes: 7