Getting name of configuration section registered for a certain type in .net
I have a custom configuration section for a library, and I would like to load my configuration object from the library itself.
Am I obliged to fix the configuration section group and name, e.g.<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyGroup">
<section name="MySection" type="MyAssembly.MySection, MyAssembly"/>
</sectio开发者_JAVA百科nGroup>
</configSections>
<MyGroup>
<MySection something="xxx" />
</MyGroup>
</configuration>
MySection cfg = (MySection)ConfigurationManager.GetSection("MyGroup/MySection");
or is there a way to get the path of the section registered for a given type, so that e.g. if the user has put the configuration section under a group with a different name I can still get it?
Something like<sectionGroup name="AnotherGroupName">
<section name="MySection" type="MyAssembly.MySection, MyAssembly"/>
</sectionGroup>
string sectionPath = SomeClass.GetSectionPath(typeof(MySection));
MySection cfg = (MySection)ConfigurationManager.GetSection(sectionPath);
There's a very good way to prevent the user from renaming a group. Hard-code the group name in your code so that it will no longer work when she messes with the name. Accommodating such arbitrary changes makes little sense and causes more problems than it solves. If you are worried about name collisions, you could certainly add a public property that allows the client code to override the group name.
精彩评论