[ACCEPTED]-Using environment variables for .config file in .NET-.net

Accepted answer
Score: 29

Yes, that's possible! Suppose you have something 4 like that in your config:

    <add key="mypath" value="%DLLPATH%\foo\bar"/>

Then you can easily 3 get the path with:

var pathFromConfig = ConfigurationManager.AppSettings["mypath"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathFromConfig);

ExpandEnvironmentVariables(string s) does the magic by replacing 2 all environment variables within a string 1 with their current values.

Score: 7

Is this a configuration entry that you're reading, or 15 is .NET reading it? If you're reading it 14 yourself, you can do the appropriate substitution 13 yourself (using Environment.ExpandEnvironmentVariables to do the lot or Environment.GetEnvironmentVariable if you 12 want to be more selective).

If it's one that 11 .NET will be reading, I don't know of any 10 way to make it expand environment variables. Is 9 the config file under your control? Could 8 you just rewrite it?

In fact, even if you 7 can do the substitution, is that really what 6 you want to do? If you need to specify the 5 full path to a DLL, I suspect you'll need 4 to find it via the DLLPATH (checking for its 3 presence in each part of the path) and then 2 subtitute %DLLPATH%\Foo.dll with the full 1 path to Foo.dll.

More Related questions