asp.net代碼中修改web.config節點的具體方法
來源:互聯網
上載者:User
但是這個變數不會一個固定的值,會根據實際情況而發生變化,比如在需要讀取一個設定檔的路徑,而這個路徑是網站發布的實際硬碟路徑,如果直接是編譯時間狀態,沒有問題。但是如果網站iis更換路徑,就需要修改這個web.config中的參數。如果能將這個編譯時間狀態修改為運行時狀態,那將更為合理和方便。這就需要存在一種在代碼中能夠動態修改web.config的方案。
代碼
複製代碼 代碼如下: /// <summary>
/// 寫入web.config
/// </summary>
/// <param name="item">appSettings等</param>
/// <param name="key">鍵</param>
/// <param name="value">值</param>
public void WriteConfig(string item, string key, string value)
{
if (item == "")
{
item = "appSettings";
}
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
AppSettingsSection appSection = (AppSettingsSection)config.GetSection(item);
if (appSection.Settings[key] == null)
{
appSection.Settings.Add(key, value);
config.Save();
}
else
{
appSection.Settings.Remove(key);
appSection.Settings.Add(key, value);
config.Save();
}
}