A while ago, I needed a way to defer settings to environment variables in a .NET application written in C#.
The easiest way to do this is to keep the same syntax as for expanding environment variables in batch files: use the %ENVIRONMENTVARIABLE% syntax (not the delayed expansion !ENVIRNMENTVARIABLE! syntax).
The reason is that there is a Windows API function ExpandEnvironmentStrings that handles all the expansion magic.
Don’t P/Invoke that function yourself, as there is already a very nice Environment.ExpandEnvironmentVariables wrapper since the .NET framework 1.1 that handles all the gory details for you (like marshalling the strings, making sure that lpDst
contains enough space for the expansion).
–jeroen