Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing File to Temp Folder

Tags:

c#

path

io

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

like image 737
BlueRay101 Avatar asked Nov 21 '13 20:11

BlueRay101


People also ask

How do I create a tmp file?

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.

How do I create a temp folder?

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".

How do you temp files?

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.


2 Answers

string result = Path.GetTempPath(); 

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

like image 54
EkoostikMartin Avatar answered Oct 03 '22 19:10

EkoostikMartin


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"); } 
like image 26
Steve Avatar answered Oct 03 '22 18:10

Steve