Reading AppSettings from a secondary webconfig

I created a second web configuration and put it in a folder:

~ / Configuration / OtherConnections.config

My configuration file looks like this:

<?xml version="1.0"?> <configuration> <appSettings> <add key="serverurl" value="http://serverUrl" /> <add key="UserName" value="myUser" /> <add key="Password" value="XXXXXXX" /> </appSettings> </configuration> 

When I try to read a value from one of the elements, for example:

 string connectionInfo = ConfigurationManager.AppSettings["UserName"]; 

I do not get the value back. Is it because the web config is in a folder or is there something else in this web application?

+4
source share
3 answers

I do not get the value back. Is it because the web config is in the folder ...?

No, not a folder, but a file name. You can use ~/Configuration/Web.config , but then you must explicitly open it:

 var config = WebConfigurationManager.OpenWebConfiguration("~/Configuration"); 

And then read from it:

 string url = config.AppSettings.Settings["serverurl"].Value; 

Note that you cannot specify (and therefore do not change) the actual name of the web.config . Just a folder.

+4
source

you can have only one web.config file for each web folder

In any case, there are towing options:

  • In IIS Manager, you need to configure the subfolder as a new application. It uses the web.config file from the running application.

  • Another option is to use a single configuration file and add a <location> section to segment the file to act differently for some folders or files. (which I would suggest more details here )

+2
source

You can access multiple configuration files using the WebConfigurationmanager method. add namespace:

 using System.Web.Configuration; 

So, to access appSettings

../SomeProjectFolder/Environment/Web.config , you can do:

 var config = WebConfigurationManager.OpenWebConfiguration("~/SomeProjectFolder/Environment/"); string username = config.AppSettings.Settings["username"].Value; 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1402456/


All Articles