I recently saw a question posted on working with configuration files in .NET.
> I wanted to do something like > > <appSettings>> <Servicing>> <add key="Report1" value="???"/>> <add key="Report2" value="???"/>> <add key="Report3" value="???"/>> </Servicing>> </appSettings>
The answer is documented in MSDN, but you need to combine several help topics to get the complete picture. So this one's for those who program via a web search engine.
When you use the appSettings element in your configuration file, it requires the following structure:
<appSettings> <add key="keyname" value="value" /> <remove key="keyname"/> <clear /></appSettings>
Each keyname value is unique (hence, the attribute name "key"). The only valid child element names of "appSettings" are add, remove, and clear. So, attempting to add your own element as a child of appSettings will not work.
If you need something more flexible than this, there are several ways to create custom configuration sections. There are several configuration section handlers provided by .NET. If you would like the return value to be a name/value pair contained in a System.Collections.Specialized.NameValueCollection, use a NameValueSectionHandler. If instead you want to have the return stored in a System.Collections.Hashtable, use a DictionarySectionHandler.
Both DictionarySectionHandler and NameValueSectionHandler use the same structure as the appSettings element (noted above), with one exception: you would use your own element name in place of "appSettings". Further, you can define custom groups of configuration sections.
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <sectionGroup name="MyCustom"> <section name="Servicing" type="System.Configuration.NameValueSectionHandler" /> <section name="Maintaining" type="System.Configuration.DictionarySectionHandler" /> </sectionGroup> </configSections> <MyCustom> <Servicing> <add key="Report1" value="value1" /> <add key="Report2" value="value2" /> <add key="Report3" value="value3" /> </Servicing> <Maintaining> <add key="Page1" value="value4" /> <add key="Page2" value="value5" /> <add key="Page3" value="value6" /> </Maintaining> </MyCustom></configuration>
The code to access the sections is simple once you have everything in place.Imports System.ConfigurationImports System.CollectionsImports System.Collections.Specialized
Sub Main() Dim col As NameValueCollection col = CType(ConfigurationSettings.GetConfig("MyCustom/Servicing"), NameValueCollection) Console.WriteLine(col("Report1"))
Dim hash As Hashtable hash = CType(ConfigurationSettings.GetConfig("MyCustom/Maintaining"), Hashtable) Console.WriteLine(hash("Page1")) End Sub
The output to the Console window would be:
PingBack from http://www.hilpers.it/2651316-web-config