I have some code in a class library built to target the .Net Framework 4 Client Profile. The code accesses the configuration of the consuming applications. For client apps (WinForms apps, console apps, etc.) getting the right object for App.Config is easy:
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
My class library also needs to work for web applications. The proper way to get access to Web.Config is also easy:
WebConfigurationManager.OpenWebConfiguration("~");
The problem is that WebConfigurationManager is part of System.Web which is not available as part of the .Net Framework 4 Client Profile.
Is there a way I can write my code or structure my project so that it will work in both cases? It needs to run well enough to access app.config on systems that only have the client profile installed. It also needs to be able to access web.config when necessary. Perhaps there’s some way I can dynamically load system.web or another assembly when it is available and when it is needed?
As mentioned by Davide Piras,
ConfigurationManager.AppSettings[]will work for the entries that are in the AppSettings section. Outside of that section,ConfigurationManager.GetSection()can be used.Strangely, the return value on
ConfigurationManager.GetSection()isn’t the same as the return value onConfiguration.GetSection(). The ConfigurationManager version doesn’t return an object that you can cast to anAppSettingsSectionor whatever. Instead you have to cast it to aSystem.Collections.Specialized.NameValueCollection. However, as long as you only are looking to work with key/value strings it works well enough. The complete code looks like this: