.resources 擴展名來自于在將 .resx 文件作為資源嵌入之前 Visual Studio .NET 處理該文件時所使用的工具。工具名稱是 resgen.exe,它用來將 .resx XML 格式“編譯”為二進制格式?梢允謩訉 .resx 文件編譯成 .resources 文件,如下所示:
C:\> resgen.exe Resource1.resx
在將 .resx 文件編譯成 .resources 文件以后,就可以使用 System.Resources 命名空間中的 ResourceReader 來枚舉它:
using( ResourceReader reader = new ResourceReader(@"Resource1.resources") ) { foreach( DictionaryEntry entry in reader ) { string s = string.Format("{0} ({1})= '{2}'", entry.Key, entry.Value.GetType(), entry.Value); MessageBox.Show(s); }}
除了類的名稱和輸入格式,ResourceReader 類的使用方法與 ResXResourceReader 相同,包括都不能隨機訪問命名項。
所以,雖然您可以將 .resx 文件轉換成 .resources 文件,并使用 /resource 編譯器命令行開關嵌入它,但容易得多的方法是直接在項目中讓 Visual Studio .NET 接受被標記為 Embedded Resources 的 .resx 文件,然后將它編譯進 .resources 文件并嵌入它,如圖 4、圖 5 和圖 6 所示。一旦將 .resources 文件捆綁為資源,訪問 .resources 文件中的資源就只需執行兩個步驟的過程:
// 1. Load embedded .resources fileusing( Stream stream = assem.GetManifestResourceStream( this.GetType(), "Resource1.resources") ) { // 2. Find resource in .resources file using( ResourceReader reader = new ResourceReader(stream) ) { foreach( DictionaryEntry entry in reader ) { if( entry.Key.ToString() == "MyString" ) { // Set form caption from string resource this.Text = entry.Value.ToString(); } } }}
因為 ResourceReader 和 ResXResourceReader 都需要該兩步過程才能找到具體的資源,因此 .NET 框架提供了 ResourceManager 類,該類公開了一個更簡單的使用模型。

資源管理器
ResourceManager 類也來自 System.Resources 命名空間,該類包裝了 ResourceReader,用于在構造時枚舉資源,并使用其名稱公開它們:
public Form1() { ... // Get this type's assembly Assembly assem = this.GetType().Assembly; // Load the .resources file into the ResourceManager // Assumes a file named "Resource1.resx" as part of the project ResourceManager resman = new ResourceManager("ResourcesApp.Resource1", assem); // Set form caption from string resource this.Text = (string)resman.GetObject("MyString"); // The hard way this.Text = resman.GetString("MyString"); // The easy way}
文章來源于領測軟件測試網 http://www.kjueaiud.com/