
In the Windows operating system, environment variables are used to insert strings specific to the operating system's current setup. With the Environment ExpandEnvironmentVariables method, you can expand these encoded variables directly in your C# program.
This C# article shows how to use the Environment.ExpandEnvironmentVariables method.
This program is very simple: it loops over a string array of environment variable string literals (they begin and also end with % characters). Next, we call Environment.ExpandEnvironmentVariables on each string literal and write the substituted result.
Program that expands environment variables [C#]
using System;
class Program
{
static void Main()
{
string[] variables =
{
"%WINDIR%",
"%HOMEDRIVE%",
"%USERNAME%",
"%COMPUTERNAME%"
};
foreach (string v in variables)
{
string result = Environment.ExpandEnvironmentVariables(v);
Console.WriteLine(result);
}
}
}
Output
C:\Windows
C:
Sam2
SAM-PC2
Note. The ExpandEnvironmentVariables method will expand more than one variable in a string in a call. Also you can have other characters in the string and it will leave those untouched. Some environment variables, such as %RANDOM% and %DATE%, are not supported according to my testing.
In programs that must handle encoded environment variables, it is probably much better to use ExpandEnvironmentVariables on the string input rather than replacing them yourself. This will yield standard behavior for the Windows operating system and also is much easier to maintain.
.NET Framework Info