Specifically Getting the System TEMP Path in C#
Asked Answered
M

1

13

I am using the System.IO.Path.GetTempPath() method to retrieve the temporary folder from environment variables. However, I am finding that this will always return the TEMP or TMP variable for the current User if it exists otherwise it will return the System TEMP or TMP variable.

Is there a way to always get the System TEMP variable?

I am aware of several other questions on SO about the Path.GetTempPath() method where answers are referencing the documentation from MSDN about how this method decides what to return. I am aware of the behavior of this method from MSDN and I am asking if there is another way to ensure I am getting the System Temporary Folder.

Micronesia answered 20/3, 2015 at 18:41 Comment(0)
C
29

Perhaps you are looking for the Environment.GetEnvironmentVariable method.

This usage gives you the user's %TEMP% folder:

Environment.GetEnvironmentVariable("TEMP");

such as C:\Users\MyUserName\AppData\Local\Temp

And this gives you the system's %TEMP% folder:

Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine);

such as C:\WINDOWS\TEMP

Cocktail answered 20/3, 2015 at 19:0 Comment(5)
I'm not the downvoter, but I suspect that you were downvoted because while you did attempt to answer the question, you didn't say how to use Environment.GetEnvironmentVariable, i.e. what arguments to pass it, etc. In particular, the OP wanted to know how to "get the System TEMP variable", and you didn't say how to do that. In other words, your answer is best incomplete.Urbanist
@WaiHaLee, thanks for your inputs. Have edited my answer now to give the parameters to be passed. Hope this makes the answer more complete.Cocktail
I came across this in my research and must have missed the target parameter. I ended up deciding to use the common app data folder instead of system temp in order to avoid any potential for issues with these environment variables.Micronesia
This doesn't seem to work for me, probably because those environment variables aren't reliable enough across multiple versions of Windows.Pepita
Neither TMP nor TEMP environment variables need to be set. You must therefore also fall back to the default location, so the progressions should be TMP, then TEMP if TMP does not exist. If neither exist use Path.GetTempPath(), which will give you the system default. Note, that this only works on Windows. If you are using C# on other platforms, you need to know which environment variables tell you the temp folder for those.Fission

© 2022 - 2024 — McMap. All rights reserved.