3

I know that I can query any environment variable by calling:

System.Environment.GetEnvironmentVariable(); 

Now for example, I want the value of windir, that is %SystemRoot%. However, the function interpretes it as C:\Windows (which is the value of SystemRoot).

I get the same behaviour by querying the registry key with Registry.LocalMachine.OpenSubKey()

Is there a way to get variable names from an environment variable instead of their paths? (I need it in order to easily switch between multiple installed versions of a SDK I work with.)

1
  • PATH tends to be a very messy affair with a mix of string literals and environment %variable% names. You'd have to first retrieve the value without getting the %variables% expanded. But if you get a string literal then you cannot know that there might be a variable name for it. Commented Dec 14, 2018 at 14:49

2 Answers 2

2

As far as I know, the only way to do that, is to read the environment variable directly from the registry and specify that you do not want it expanded:

registryKey.GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames); 

See the docs for RegistryValueOptions.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is what I was looking for. Thank you very much.
2

The fact that %WINDIR% and %SYSTEMROOT% have the same value is a mere coincidence. It's obvious why they would be, but they are still independent variables. Changing one would not result in the other being changed.

You would have to write something manually that sought out other environmental variables with the same value and substituted whatever replacement variable you had in mind, e.g. %SYSTEMROOT%.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.