Environment Variable in app.config appSettings file attribute

Viewed 1758

How do I point my app.config appSettings' external file to point to a path using an environment variable? The below is not recognized:

<appSettings file="%AppData%\MyApp\MySettingsFile.config" />

However, absolute paths are recognized, even though they are not within the hierarchy of the output path of the assembly, such as:

<appSettings file="C:\MyApp\MySettingsFile.config" />
2 Answers

You can do it as below:

If your changes in app.config as below:

<appSettings file="%AppData%\MyApp\MySettingsFile.config" />

then in .cs file, just expand the environment variable using Environment.ExpandEnvironmentVariables as below:

var pathConfig = ConfigurationManager.AppSettings["file"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathConfig);

expandedPath will have the expanded path.

Related