但是這個(gè)變量不會(huì)一個(gè)固定的值,會(huì)根據(jù)實(shí)際情況而發(fā)生變化,比如在需要讀取一個(gè)配置文件的路徑,而這個(gè)路徑是站點(diǎn)發(fā)布的實(shí)際硬盤路徑,如果直接是編譯時(shí)狀態(tài),沒有問題。但是如果站點(diǎn)iis更換路徑,就需要修改這個(gè)web.config中的參數(shù)。如果能將這個(gè)編譯時(shí)狀態(tài)修改為運(yùn)行時(shí)狀態(tài),那將更為合理和方便。這就需要存在一種在代碼中能夠動(dòng)態(tài)修改web.config的方案。
代碼
復(fù)制代碼代碼如下:
/// <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();
}
}