2012-12-05 25 views
2

我只是通过这个代码读取web.config文件作为添加appSettings部分通过C#代码的web.config

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

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

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

它正常工作时appSettings出现在web.config文件。

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

+0

通常您只需编辑配置文件。你为什么试图修改它有问题? –

+0

@Jason Meckley它是我的作品 – GowthamanSS

回答

0

你可以检查你的web.config是否有appSettings标签或不这样;

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

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

我找不到任何动态地添加appSettings标签却发现关于可能是相当有用的.NET配置三部分组成的系列。

+0

其k如何添加appsettings标签 – GowthamanSS

+0

@GowthamanSS更新了我的问题。 –

1

在这里,我添加新的应用程序键 “的myKey” 与价值 “myvalue的”:

 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),添加新的密钥并保存。

快乐编码!