Web.config文件假設有如下需要管理的配置信息:
<appSettings>
<add key="SiteTitle" value="站點名稱" />
<add key="SiteUrl" value="主頁網址" />
<add key="SiteLogo" value="站點Logo" />
<add key="SiteBanner" value="站點Banner" />
<add key="SiteEmail" value="聯繫Email" />
</appSettings>
實現的c#核心代碼:
一、將Web.config中的相關信息讀入TextBox
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
//將Web.config中的相關值填入TextBox
this.txtTitle.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteTitle"];
this.txtUrl.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteUrl"];
this.txtLogo.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteLogo"];
this.txtBanner.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteBanner"];
this.txtEmail.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteEmail"];
}
}
二、將修改後的內容寫入Web.config
private void btnSave_Click(object sender, System.EventArgs e)
{
string filename=Server.MapPath("web.config");
string KeyName;//鍵名稱
XmlDocument xmldoc= new XmlDocument();
try
{
xmldoc.Load(filename);
}
catch
{
Response.Write("<script>alert('讀文件時錯誤,請檢查 Web.config 文件是否存在!')</script>");
return;
}
XmlNodeList DocdNodeNameArr=xmldoc.DocumentElement.ChildNodes;//文檔節點名稱數組
foreach(XmlElement DocXmlElement in DocdNodeNameArr)
{
if(DocXmlElement.Name.ToLower()=="appsettings")//找到名稱爲 appsettings 的節點
{
XmlNodeList KeyNameArr=DocXmlElement.ChildNodes;//子節點名稱數組
if ( KeyNameArr.Count >0 )
{
foreach(XmlElement xmlElement in KeyNameArr)
{
KeyName=xmlElement.Attributes["key"].InnerXml;//鍵值
switch(KeyName)
{
case "SiteTitle":
xmlElement.Attributes["value"].Value=this.txtTitle.Text;
break;
case "SiteUrl":
xmlElement.Attributes["value"].Value=this.txtUrl.Text;
break;
case "SiteLogo":
xmlElement.Attributes["value"].Value=this.txtLogo.Text;
break;
case "SiteBanner":
xmlElement.Attributes["value"].Value=this.txtBanner.Text;
break;
case "SiteEmail":
xmlElement.Attributes["value"].Value=this.txtEmail.Text;
break;
}
}
}
}
}
try
{
xmldoc.Save(filename);
Response.Write("<script>alert('OK,信息已保存!')</script>");
}
catch
{
Response.Write("<script>alert('寫文件時錯誤,請檢查 Web.config 文件是否存在!')</script>");
return;
}
}