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.

Brian
  • 2,702
  • 5
  • 37
  • 71

1 Answers1

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

sudheeshix
  • 1,541
  • 2
  • 17
  • 28
  • 1
    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. – Wai Ha Lee Mar 20 '15 at 19:24
  • 1
    @WaiHaLee, thanks for your inputs. Have edited my answer now to give the parameters to be passed. Hope this makes the answer more complete. – sudheeshix Mar 20 '15 at 20:43
  • 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. – Brian Mar 23 '15 at 14:08
  • This doesn't seem to work for me, probably because those environment variables aren't reliable enough across multiple versions of Windows. – kayleeFrye_onDeck Apr 16 '19 at 17:38
  • 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. – 4thex Sep 04 '20 at 12:00