資源檔是 .NET 實現多語系與資源管理的核心機制。本文詳細比較 .resx (XML 文字格式) 與 .resources (二進位編譯格式) 的特性,並分別示範 Windows Forms 與 ASP.NET Web Forms 中的應用模式與命名慣例。
resgen.exe 編譯產生的二進位格式,執行期由 ResourceManager 載入,效能較佳。手動編譯指令:resgen.exe Resource1.resx
Form.cs、Form.Designer.cs) 以巢狀結構關聯顯示。.resources 檔時,需將 Build Action 設為 Embedded Resource。Assembly asm = Assembly.GetExecutingAssembly();
ResourceManager rm = new ResourceManager("TestStrongName123.Form1", asm);
textBox1.Text = rm.GetString("First");
引入資源目錄概念,自動偵測無需手動設定 Embedded Resource:
App_GlobalResources,檔名自訂 (如 GlobalResource.resx)。App_LocalResources,檔名必須對應頁面 (如 Default.aspx.resx)。<asp:Literal ID="Literal1" runat="server" Text="<%$ Resources:LocalString1 %>" />
<asp:Literal ID="Literal3" runat="server" Text="<%$ Resources:GlobalResource, GlobalString1 %>" />
// 區域資源
Literal2.Text = (string)GetLocalResourceObject("LocalString2");
// 全域資源
Literal4.Text = (string)GetGlobalResourceObject("GlobalResource", "GlobalString2");
// 全域資源圖片
Bitmap bm = Resources.GlobalResource.GlobalSmallFail;
公文系統採用客戶端控制項策略,伺服器端控制項極少,且全球化資源需求難以預判,故資源檔僅用於字串管理;圖片等二進位資源仍以檔案替換機制為主,不納入 .resx 管理。