How to Use the custom configuration section in the web. config file A simple example of how to use the custom configuration section in the web. config file Used for demonstrationProgramThe name is MyApp, and namespace is also MyApp. 1. Edit the Web. config file Add the following content to declare a Section <Configsections> <Section name = "appconfig" type = "MyApp. appconfig, MyApp"/> </Configsections> Declared a section called appconfig 2. Edit the Web. config file Add the following content to a section <Appconfig> <Add key = "connectionstring" value = "This Is A connectionstring"/> <Add key = "usercount" value = "199"/> </Appconfig> This section contains two keys 3. Derive a class from iconfigurationsectionhandler, appconfig Implement the create method,CodeAs follows: Public class appconfig: iconfigurationsectionhandler { Static string m_connectionstring = string. empty; Static int32 m_usercount = 0; Public static string connectionstring { Get { Return m_connectionstring; } } Public static int32 usercount { Get { Return m_usercount; } } Static string readsetting (namevaluecollection NVC, string key, string defaultvalue) { String thevalue = NVC [Key]; If (thevalue = string. Empty) Return defaultvalue; return thevalue; } Public object create (Object parent, object configcontext, xmlnode section) {< br> namevaluecollection settings; try {< br> namevaluesectionhandler basehandler = new namevaluesectionhandler (); Settings = (namevaluecollection) basehandler. create (parent, configcontext, Section); }< br> catch {< br> Settings = NULL; }< br> If (settings! = NULL) {< br> m_connectionstring = appconfig. readsetting (settings, "connectionstring", String. empty); m_usercount = convert. toint32 (appconfig. readsetting (settings, "usercount", "0"); }< br> return settings; }< BR >} We map all the configurations to the corresponding static member variables and write them as read-only attributes. Similar to appconfig. connectionstring, you can access the project in the configuration file. 4. Finally, we have to do one thing. Add the following code to application_start in global. asax. CS: System. configuration. configurationsettings. getconfig ("appconfig "); After the program starts, it will read the value in the section appconfig. The system will call your own iconfigurationsectionhandler interface to read the configuration. |