c# - 通过 C# 代码将 appSettings 部分添加到 web.config

标签 c# .net web-config

我只是通过这段代码读取 web.config 文件

Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");

AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");

if (appSettingsSection != null)
{
         appSettingsSection.Settings.Remove(key);
         config.Save();
}

web.config 文件中存在 appSettings 时,它工作正常。

我的查询是在 web.config 文件中添加 appSettings 标签,如果它不存在的话。

最佳答案

在这里,我添加了值为“myValue”的新应用程序 key “myKey”:

        System.Configuration.KeyValueConfigurationCollection settings;
        System.Configuration.Configuration config;

        System.Configuration.ExeConfigurationFileMap configFile = new System.Configuration.ExeConfigurationFileMap();
        configFile.ExeConfigFilename = "App.config";
        config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, System.Configuration.ConfigurationUserLevel.None);
        settings = config.AppSettings.Settings;

        config.AppSettings.Settings.Add(new System.Configuration.KeyValueConfigurationElement("myKey", "myValue"));
        config.Save();

所以重点是加载特定的配置(添加你想要的 appSettings),添加新 key 并保存它。

编码愉快!

关于c# - 通过 C# 代码将 appSettings 部分添加到 web.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13724661/

相关文章:

c# - 如何将 Roslyn 脚本提交用作其他 Roslyn 编译中的程序集

c# - 在 C# 中使用 ArrayPool 重用从字符串到字节数组转换的内存?

asp.net - 如何将配置转换应用于外部配置文件

c# - ResponseRewrite 后 session 为空

c# - 有关通过 Windows Installer 安装应用程序的问题

c# - 如果当前用户不属于 [Authorize] 所需的角色,我可以自动重定向他们吗?

c# - BuildManager.AddReferencedAssembly 究竟做了什么?

c# - 从 IEnumerable<DateTime> 获取最早的日期

c# - 将 Double.NaN 与自身进行比较

asp.net - web.config hiddenSegment 只针对根目录?