首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

動態修改 .NET Resx 資源檔值的實作方案:XML 直接操作法

     編輯:關於.NET

開發中常將設定值存於 .resx 檔案(本質為 XML),但執行時如何修改其值?以全域資源 App_GlobalResources/Resource.resx 為例,包含兩個字串資源 Anm_Response、Rqi_Response。

Resx 檔案結構

<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();

注意事項

  • 修改後需重新啟動應用程式或回收應用程式集區才能生效(ASP.NET 快取機制)
  • 生產環境需考慮並發寫入鎖定機制
  • 建議僅用於管理後台等低頻修改場景
  • 正式專案推薦使用資料庫儲存動態設定,Resx 適合靜態資源

本文配套完整原始碼可供下載參考。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved