Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment Variable in app.config appSettings file attribute

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" />
like image 746
as9876 Avatar asked Aug 22 '26 18:08

as9876


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.

like image 178
bharath kumar amarnath Avatar answered Aug 24 '26 11:08

bharath kumar amarnath


"The path specified is relative to the main configuration file. For a Windows Forms application, this would be the binary folder (such as /bin/debug), not the location of the application configuration file. For Web Forms applications, the path is relative to the application root, where the web.config file is located."

https://msdn.microsoft.com/en-us/library/aa903313(v=vs.71).aspx

I'm guessing your scenario works when calling the full path because your MySettingsFile.config is still within your application heirarchy.

like image 43
Michael Ballhaus Avatar answered Aug 24 '26 10:08

Michael Ballhaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!