2

我只是通过此代码阅读 web.config 文件

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

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

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

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

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

4

2 回答 2

1

在这里,我添加了值为“myValue”的新应用程序密钥“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),添加新的密钥并保存它。

快乐编码!

于 2012-12-05T14:30:31.960 回答
0

You can check if your web.config has appSettings tag or not like this;

string s = ConfigurationManager.AppSettings["appSettings"];

if (!String.IsNullOrEmpty(s))
{
    // Key exists
}
else
{
    // Key doesn't exist
}

I couldn't find anything adding dynamically appSettings tag but found three-part series about .NET configuration that could be quite usefull.

于 2012-12-05T14:02:40.923 回答