Windows – TEMP environment variable occasionally set incorrectly

environment-variableswindows 7

Occasionally, I find my TEMP and TMP environment variables set to C:\Windows\TEMP. They should be set to %USERPROFILE%\AppData\Local\Temp, and are configured correctly in System Properties.

This manifests itself as error messages like the following:

---> System.InvalidOperationException: Unable to generate a temporary class
     (result=1).
error CS2001: Source file 'C:\Windows\TEMP\gb_pz65v.0.cs' could not be found
error CS2008: No inputs specified

…which occurs in various .NET applications (in particular Visual Studio 2010 or SQL Server Management Studio). Alternatively, SQL Server Management Studio will report:

Value cannot be null.
Parameter name: viewInfo (Microsoft.SqlServer.Management.SqlStudio.Explorer)

If I run PowerShell elevated, then $env:TEMP is set correctly. If I run PowerShell non-elevated, then it's not. I believe that it should be set correctly in both cases. If not, it's the wrong way round.

The same is true for CMD.EXE.

Rebooting fixes it, temporarily, until something breaks it again. Presumably something loaded into Explorer.exe is messing with its environment variables, but what?

The values in the registry are correct, even while this is happening:

  • HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment has TEMP = %SYSTEMROOT%\Temp
  • HKCU\Environment has TEMP = %USERPROFILE%\AppData\Local\Temp

By setting a breakpoint on shell32!RegenerateUserEnvironment with WinDbg, I'm able to trap it when it happens, but I still don't know why explorer.exe is reading the wrong environment variables.

I can reproduce it consistently by broadcasting a WM_SETTINGCHANGE message (I wrote a one-line C++ program to do this). Watching the activity in Process Monitor shows that explorer.exe doesn't even look at HKCU\Environment.

What is going on?

Best Answer

I encountered this exact same problem a few weeks ago and it's been driving me batty. I think what's causing it is an excessively long path variable. I found several other reports of "disappearing" environment variables around the web and some suggestion that it was related to a long path.

I had a look at mine, and it turned out that some buggy installers had duplicated all the entries (some more than once). There must be a buffer overrun bug buried in explorer.exe somewhere. Anyway, when I removed the duplicates and hit OK, my TEMP variable suddenly re-appeared (with the correct value) in all apps I launched from explorer.

Related Question