Sometimes we may need to expand paths like "%systemroot%\program.exe" etc programmatically. Specially values in the registry are encoded in this format. The .net framework provides us a straightforward method using which we can easily convert strings containing such special variables into their values.
Environment.ExpandEnvironmentVariables() method
The Environment.ExpandEnvironmentVariables() method is used in expanding strings containing such environment variables. Let's take a look at a simple code snippet.
string str = Environment.ExpandEnvironmentVariables(@"%systemroot%\notepad.exe");MessageBox.Show(str);
Will output "c:\Windows\notepad.exe". The ExpandEnvironmentVariables() method expands all the environment variables found inside the string provided. The environment variables are marked using "%" character at the beginning and at the end of the variable for example "%username%".
Listing all the environment variables
If you are interested to know the name/values of all environment variables, the following code snippet will print out all.
foreach(System.Collections.DictionaryEntry v in Environment.GetEnvironmentVariables())Console.WriteLine( v.Key + "|"+ v.Value);
Environment.ExpandEnvironmentVariables() method can be very useful in some special situations like working with registry, reading some config files etc.
Happy coding!