Tutorial :Load and Query Web Configuration



Question:

Is it somehow possible to load a web.config file in a WinForms app and query the resulting configuration, instead of using XML to find some less than semantic 'add' element?


Solution:1

You need to add a reference to System.Web then the goes would go something like:

using System.Web.Configuration  WebConfigurationManager webCfg = WebConfigurationManager.OpenWebconfiguration("/WebApp");    // Edit/Query the configuration  webConfig.AppSettings.Settings.Add("NewSetting","SomeValue");  webConfig.AppSettings.SectionInformation.ForceSave = true;    webConfig.Save();  

If you want to access a configuration section that does not have a public interface like system.diagnostics then you can use the generic configuration classes. Add a reference to System.Configuration and try something like:

ConfiguationSection sysDiagnostics = webConfig.GetSection("system.diagnostics");  ConfigurationElementCollection sources = sysDiagnostics.ElementInformation.Properties["sources"].Value as ConfigurationElementCollection;  foreach (ConfigurationElement source in sources)  {      ConfigurationElementCollection listeners = source.ElementInformation.Properties["listeners"].Value as ConfigurationElementCollection;       foreach (ConfigurationElement listener in listeners)       {          Console.WriteLine(listener.ElementInformation.Properties["name"].Value.ToString());       }  }  


Solution:2

After trying, albeit very quickly, all the suggestions above, with varying degrees of failure, I used an XmlDocument and XPath, and did the job with two lines of code and one imported namespace, without requiring additional assembly references.

WebConfigurationManager.OpenWebConfiguration("/", "My Website", null)  

The above requires a virtual path, which means what to a WinForms application? I did state that I needed to open a web.config 'in a WinForms app'.

And I improved my XPath an iota. :-)


Solution:3

You can use the WebConfigurationManager.OpenWebConfiguration method in the System.Web.Configuration namespace.

Example:

System.Configuration.Configuration config =          WebConfigurationManager.OpenWebConfiguration("/", "My Website", null) as System.Configuration.Configuration;    KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;  

This gets the appsettings block of website 'My Website'. Just modify the first parameter which is the virtual path to the config file.


Solution:4

Hum, did you tried to :

Using System.Web.Configuration;  

or

Using System.Configuration;  

with that you will should have access to the ConfigurationManager object which will give you access to the web.config file.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »