.NET 資源檔(.resources / .resx)讓開發者將圖片、字串、圖示、音訊等非程式碼資產與邏輯分離,支援:
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。
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;
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 同理
}
}
Resources.zh-Hant.resx、Resources.en.resx 等文化特性檔,系統自動依 Thread.CurrentThread.CurrentUICulture 選取。