開發中常將設定值存於 .resx 檔案(本質為 XML),但執行時如何修改其值?以全域資源 App_GlobalResources/Resource.resx 為例,包含兩個字串資源 Anm_Response、Rqi_Response。
<data name="Anm_Response" xml:space="preserve">
<value>333333</value>
</data>
<data name="Rqi_Response" xml:space="preserve">
<value>44</value>
</data>
資料儲存在 <data> 節點,值位於 <value> 子節點。透過 XML 操作即可動態修改。
using System.IO;
using System.Collections;
using System.Globalization;
using System.Xml;
using System.Resources;
protected void btnModify_Click(object sender, EventArgs e)
{
string filename = "Resource.resx";
// 取得實體路徑
filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + filename;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
// 取得所有 data 節點
XmlNodeList nlist = xmlDoc.GetElementsByTagName("data");
foreach (XmlNode xnVal in nlist)
{
if (xnVal.Attributes["xml:space"].Value == "preserve")
{
string sName = xnVal.Attributes["name"].Value;
switch (sName)
{
case "Anm_Response":
xnVal.InnerText = txbAnmResponse.Text;
break;
case "Rqi_Response":
xnVal.InnerText = txbRqiResponse.Text;
break;
default:
break;
}
}
}
// 儲存變更
xmlDoc.Save(filename);
}
string sAnmResponse = HttpContext.GetGlobalResourceObject("Resource", "Anm_Response").ToString();
本文配套完整原始碼可供下載參考。