I encapsulated a class library, which was originally intended for reuse by myself,CodeAs follows:
1 /// <Summary> 2 /// Write configuration file value 3 /// </Summary> 4 /// <Param name = "key"> Key </Param> 5 /// <Param name = "value"> Value </Param> 6 /// <Returns> True is returned if the write is successful. Otherwise, false is returned. An exception occurs. </Returns> 7 Public Static Bool Write ( String Key, String Value) 8 { 9 Try 10 { 11 Configuration Config = Configurationmanager. openexeconfiguration (configurationuserlevel. None ); 12 Config. etettings. settings [Key]. value = Value; 13 14 Config. appsettings. sectioninformation. forcesave =True ; 15 Config. Save (configurationsavemode. modified ); 16 17 18 // In debug mode, the content in the actual file is not changed. after release, the content is changed. 19 Configurationmanager. refreshsection ( " Appsettings " ); 20 21 Return True ; 22 } 23 Catch (Exception ex) 24 { 25 Return False ; 26 } 27 }
The function of this method is to save the value to the deleetting node in the configuration file. But I don't want to encounter the title problem when I use it on a Web site today.
The solution is to rewrite a method for the web site:
/// <Summary> /// Write web configuration file value /// </Summary> /// <Param name = "key"> Key </Param> /// <Param name = "value"> Value </Param> /// <Returns> True is returned if the write is successful. Otherwise, false is returned. An exception occurs. </Returns> Public Static Bool Writewebconfig ( String Key, String Value ){ Try {Configuration config = Webconfigurationmanager. openwebconfiguration ( " ~ " ); Config. etettings. settings [Key]. Value = Value; config. etettings. sectioninformation. forcesave = True ; Config. Save (configurationsavemode. modified ); // In debug mode, the content in the actual file is not changed. after release, the content is changed. Configurationmanager. refreshsection ( " Appsettings " ); Return True ;} Catch (Exception ex ){ Return False ;}}
Done.
The webconfigurationmanager class is in system. Web. dll. Just add a reference.