2012-12-05 78 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),添加新的密鑰並保存。

快樂編碼!