I want to use StreamWriter
to write a file to the temp folder.
It might be a different path on each PC, so I tried using %temp%\SaveFile.txt
but it didn't work.
How can I save to the temp folder, using environmental variables?
And for example, can I use an environmental variable for storing files in %appdata%
?
To create and use a temporary file The application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.
Open your File Explorer (it's usually the first button on your desktop taskbar, looks like a folder). Go to the "This PC" section on the left, and then double-click your C: drive. On the Home tab at the top, click "New Folder" and name it "Temp".
Temporary files are used by your system to store data while running programs or creating permanent files, such as Word documents or Excel spreadsheets. In the event that information is lost, your system can use temporary files to recover data.
string result = Path.GetTempPath();
https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath
The Path class is very useful here.
You get two methods called
Path.GetTempFileName
Path.GetTempPath
that could solve your issue
So for example you could write: (if you don't mind the exact file name)
using(StreamWriter sw = new StreamWriter(Path.GetTempFileName())) { sw.WriteLine("Your error message"); }
Or if you need to set your file name
string myTempFile = Path.Combine(Path.GetTempPath(), "SaveFile.txt"); using(StreamWriter sw = new StreamWriter(myTempFile)) { sw.WriteLine("Your error message"); }
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