如何通过代码修改web.config文件中的密钥?

时间:2016-12-23 13:26:00

标签: c# asp.net xml iis web-config

如果我在网络应用程序的web.config文件中:

<appSettings>
    <add key="DD" value="567_Access"/>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
</appSettings>

我知道如何阅读appSettings部分中的数据,如下所示:

 string accessD = ConfigurationManager.AppSettings["DD"];

但我想知道如何修改(设置) appSettings中某个键的值 通过代码?

(我希望在某些情况下通过对此值的特定检查来停止应用程序)

1 个答案:

答案 0 :(得分:1)

System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();
configFile.ExeConfigFilename = "ConsoleTester.exe.config";  //name of your config file, can be from your app or external
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);
System.Configuration.KeyValueConfigurationCollection settings = config.AppSettings.Settings;
settings["DD"].Value = "007_Access";
config.Save();