Writing File to Temp Folder

C#IoPath

C# Problem Overview


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%?

C# Solutions


Solution 1 - C#

string result = System.IO.Path.GetTempPath();

https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath

Solution 2 - C#

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");
}

Solution 3 - C#

You can dynamically retrieve a temp path using as following and better to use it instead of using hard coded string value for temp location.It will return the temp folder or temp file as you want.

string filePath = Path.Combine(Path.GetTempPath(),"SaveFile.txt");

or

Path.GetTempFileName();

Solution 4 - C#

System.IO.Path.GetTempPath()

The path specified by the TMP environment variable. The path specified by the TEMP environment variable. The path specified by the USERPROFILE environment variable. The Windows directory.

Solution 5 - C#

For %appdata% take a look to

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlueRay101View Question on Stackoverflow
Solution 1 - C#EkoostikMartinView Answer on Stackoverflow
Solution 2 - C#SteveView Answer on Stackoverflow
Solution 3 - C#Thilina HView Answer on Stackoverflow
Solution 4 - C#PacmanView Answer on Stackoverflow
Solution 5 - C#user3014562View Answer on Stackoverflow