How to access additional options in App.config?
Basically, App.config and Web.config are easy to deal with when it comes to connection strings and configuration key-value pairs.
But how to access additional sections of those two files?
The only way I can find implies that configurati开发者_如何学Goon/configSections/section
must be created in order to be able to add additional settings to the configuration files. This is false, since several .NET components actually access custom settings without using configuration/configSections/section
. For example, when dealing with diagnostics settings, I can have the section:
<system.diagnostics>
<trace autoflush="true"/>
<sources>
<source name="Samples">
<listeners>
<add name="ConsoleListener" type="System.Diagnostics.ConsoleTraceListener"/>
</listeners>
</source>
</sources>
</system.diagnostics>
without being required to add any configSection to the file.
How to do the same thing in my own code?
The section you mention isn't undefined, it's defined in the machine configuration file (which is global for .NET). If you need to have custom sections, you will need to define them in the beginning of the file and define the classes that represent them, so .NET knows how to handle the corresponding objects.
If you only need to access some setting without getting the objects and everything, you can define the section as using just ConfigSectionHandler
and then accessing the XML document directly like this (after all, the config file is just another XML file).
I would strongly suggest to not go the direct access route and instead use the regular way, i.e. this guide. It will save you some trouble by validating everything and making it easily accessible from code. It is a PITA to set up initially, but it's worth it.
The comment by @Vladislav covers it. The config section need to always be defined, but not necessarily in the web/app config file, because config files have a heirarchy. SO the standard sections are defined in a standard machine.config file.
If you have a need for sections that are accessible across multiple applications, you can amend the machine.config file and specify them in there. However, this is not something you should do in 99.99% of programming situations. And all it does is hide the section details from the developer.
Bear in mind that if you were to do this, you would have to provide the dll that defines this section to all the computers, and keep it updated whichever application amended it. There is a sigificant maintenence overhead in this, so you would have to be absolutely sure that there was a real benefit in doing this.
The simple answer to you question is yes you can do it, but you never should. Very occasionally, this is wrong.
精彩评论