[c#] Writing File to Temp Folder

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

This question is related to c# io path

The answer is


For %appdata% take a look to

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

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.


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();

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to io

Reading file using relative path in python project How to write to a CSV line by line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder Exception: Unexpected end of ZLIB input stream How to get File Created Date and Modified Date Printing Mongo query output to a file while in the mongo shell Load data from txt with pandas Writing File to Temp Folder How to get resources directory path programmatically ValueError : I/O operation on closed file

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)