If you use Environment.GetEnvironmentVariable("Path") to get the Path and later set it via Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine), you will kill your path, since the former retrieves it from the process’s environment block, which includes both Machine and User environments (and more sometimes). I did this block-headed thing, and set my path a couple of times, and it grew to be too long and got truncated. Ouch. Developer tools stop working quickly if that happens.
Thankfully, the machine environment on a Windows NT kernel based OS is controlled by a key in the System key of the HKLM hive: HKEY_LOCAL_MACHINESystemCurrentControlSetControlSession ManagerEnvironment. This means that on a successful boot, the control set is copied over to a second key called ControlSet002. This is how "Last Known Good Configuration" recovery is accomplished – Windows just uses this backup key if you hit F8 and "Last Known Good" at boot. This means my old path should be in HKEY_LOCAL_MACHINESystemControlSet002ControlSession ManagerEnvironment. Bingo, it was. What a relief.
So, don’t forget to call your Environment.GetEnvironmentVariable and Environment.SetEnvironmentVariable methods with matching EnvironmentVariableTarget values, unless you have a carefully considered reason.
Filed under: Uncategorized