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

C# 資源檔完整指南:建立、嵌入與讀取圖片、字串、圖示等資源

     編輯:關於C語言

為何使用資源檔?

.NET 資源檔(.resources / .resx)讓開發者將圖片、字串、圖示、音訊等非程式碼資產與邏輯分離,支援:

  • 多語言本地化(文化特性資源回退機制)
  • 單一檔案部署(嵌入組件)
  • 執行期動態載入、版本管理
  • 敏感資料加密保護

建立資源檔:ResourceWriter 方式


using System.Resources;
using System.Drawing;

ResourceWriter rw = new ResourceWriter("My.resources");

// 加入圖示
Icon ico = new Icon("Demo.ico");
rw.AddResource("demo.ico", ico);

// 加入圖片
Image img = Image.FromFile("ok-off.png");
rw.AddResource("ok-off.png", img);

// 加入字串
rw.AddResource("MyStr", "從資源檔讀取的字串!");

rw.Generate(); rw.Close();

注意:執行前需確認來源檔案(.ico/.png)存在於執行目錄。

嵌入資源至組件

編譯時加入 /res 參數:

csc.exe /res:My.resources use.cs

或在 Visual Studio 中:專案屬性 → Resources → 加入現有檔案,自動生成 Resources.resx 並設為 Embedded Resource。

讀取資源:ResourceManager


using System.Resources;
using System.Reflection;

ResourceManager rm = new ResourceManager("Images", Assembly.GetExecutingAssembly());

// 讀取字串(自動依 CurrentUICulture 回退)
string s = rm.GetString("MyStr");

// 讀取圖片/圖示(需 Unboxing 轉型)
Icon ico = (Icon)rm.GetObject("demo.ico");
Image img = (Image)rm.GetObject("ok-off.png");

裝箱/拆箱 與強型別資源

GetObject 回傳 object,需轉型(拆箱)。Visual Studio 自動生成的 Properties.Resources 類別提供強型別屬性:


// 直接使用強型別,無需轉型
this.Icon = Properties.Resources.demo;
picBox.Image = Properties.Resources.ok_off;
lbl.Text = Properties.Resources.MyStr;

WinForms 完整範例:按鈕狀態圖片切換


public class Form1 : Form {
    private Label lblOK, lblCancel, lblResource;
    private ResourceManager rm;

    public Form1() {
        rm = new ResourceManager("Images", Assembly.GetExecutingAssembly());
        InitializeComponent();
    }

    private void InitializeComponent() {
        lblOK = new Label(); lblCancel = new Label(); lblResource = new Label();
        // 初始狀態
        lblOK.Image = (Image)rm.GetObject("ok-off.png");
        lblCancel.Image = (Image)rm.GetObject("cancel-off.png");
        lblResource.Text = rm.GetString("MyStr");
        this.Icon = (Icon)rm.GetObject("demo.ico");

        // 事件:滑鼠進入/離開/點擊切換圖片
        lblOK.MouseEnter += (s,e) => lblOK.Image = (Image)rm.GetObject("ok-on.png");
        lblOK.MouseLeave += (s,e) => lblOK.Image = (Image)rm.GetObject("ok-off.png");
        lblOK.Click += (s,e) => lblOK.Image = (Image)rm.GetObject("ok-down.png");
        // ... lblCancel 同理
    }
}

最佳實踐建議

  • 優先使用 .resx + 強型別類別,避免硬編碼字串鍵名拼寫錯誤。
  • 大型專案採用 資源檔分模組(如 Resources.Images、Resources.Strings)管理。
  • 本地化:建立 Resources.zh-Hant.resx、Resources.en.resx 等文化特性檔,系統自動依 Thread.CurrentThread.CurrentUICulture 選取。
  • 敏感資料(連線字串、金鑰)勿直接放入資源檔,應加密儲存或使用 Secret Manager / Key Vault。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved