简体   繁体   中英

Changing the Web.config file key value at runtime using C# without changing the structure of the file

I have the following code to change key value in Web.config file.

Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
webConfigApp.AppSettings.Settings["Email"].Value = "abc@def.com";
webConfigApp.Save();

It changes the value successfully but it also affects the file structure. I have some comments in the file that comments are gone after running the above code.

Is there any code which only updates the key value and not affects the entire file?

There is an overload on Save method that is

Save(ConfigurationSaveMode)

If you set it to Minimal it will save only the changed properties. Please take a look at https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationsavemode?view=netframework-4.8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM