Access web.config using the client profile class library

I have some code in the class library designed to target the .Net Framework 4 Client Profile. Access code for the configuration of consumer applications. For client applications (WinForms applications, console applications, etc.) Getting the right object for App.Config is very simple:

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

My class library should also work for web applications. The right way to access Web.Config is also easy:

 WebConfigurationManager.OpenWebConfiguration("~"); 

The problem is that the WebConfigurationManager is part of System.Web, which is not available as part of the .Net Framework 4 Client Profile.

Is there a way to write my code or the structure of my project so that it works in both cases? It should work well enough to access app.config on systems where only the client profile is installed. It should also have access to web.config if necessary. Perhaps there is a way that I can dynamically load system.web or another assembly when it is available and when it is needed?

+4
source share
2 answers

As already mentioned by Davide Piras, ConfigurationManager.AppSettings[] will work for entries that are in the AppSettings section. Outside of this section, you can use ConfigurationManager.GetSection() .

Strange, the return value on ConfigurationManager.GetSection() does not match the return value on Configuration.GetSection() . The ConfigurationManager version does not return an object that you can overlay on AppSettingsSection or whatever. Instead, you should point it to System.Collections.Specialized.NameValueCollection . However, while you are only going to work with the keys / string values, it works quite well. The full code is as follows:

 using System.Configuration; using System.Collections.Specialized; var settingsSection = ConfigurationManager.GetSection(sectionName) as NameValueCollection; var configValue = settingsSection[keyName]; 
+1
source

very interesting question; -)

if you need to read appSettings, just use ConfigurationManager.AppSettings , which requires System.Configuration , and check how it works in the web application. If this works, you can go, and in the end it’s a limitation that you have to put everything you need into the appSettings section or study other classes and options of the ConfigurationManger class and not use something like WebConfigurationManager

+1
source

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


All Articles