在写程序时, 可以把用到的 图标,图片,声音等外部资源,放在一个 .resx (资源文件)中. 这样的好处是不用考虑什么路径的问题.而且还对资源有保护的做用.本文描述如何创建 resx 文件,和对 resx 文件的更新修改。
1.添加引用
2. 创建新的 Resx 文件
using System.IO; using System.Resources; namespace Resx { class CreateResx { /// <summary> /// Create Resx /// </summary> /// <param name="Folder"></param> public static void Create() { string p = @"..\..\Resx\Create.resx"; //found the file exist if (!File.Exists(p)) { FileStream fs1 = new FileStream(p, FileMode.Create, FileAccess.ReadWrite); fs1.Close(); } ResXResourceWriter resourceWriter = new ResXResourceWriter(p); resourceWriter.AddResource("Name", "yanzhiyi"); //Write to file resourceWriter.Generate(); resourceWriter.Close(); } } }
3. 将 resx 文件中的数据,添加到指定的 resx 文件中 。
源文件 :
代码:
using System.Collections; using System.Collections.Generic; using System.Resources; namespace Resx { class UpdateResx { public static void BatchUpdateResx() { string Basic = @"..\..\Resx\Create.resx"; Hashtable resourceEntriesreaderBasic = new Hashtable(); //Get existing resources ResXResourceReader readerBasic = new ResXResourceReader(Basic); readerBasic.UseResXDataNodes = true; ResXResourceWriter resourceWriterBasic = new ResXResourceWriter(Basic); //System.ComponentModel.Design.ITypeResolutionService typeres = null; Hashtable resourceEntries = new Hashtable(); List<ResXDataNode> list = new List<ResXDataNode>(); if (readerBasic != null) { IDictionaryEnumerator id = readerBasic.GetEnumerator(); foreach (DictionaryEntry d in readerBasic) { //Read from file: ResXDataNode dataNode = (ResXDataNode)d.Value; list.Add(dataNode); } readerBasic.Close(); } //addList(list); string p = @"..\..\Resx\Resources.zh-CN.resx"; ResXResourceReader reader = new ResXResourceReader(p); reader.UseResXDataNodes = true; ResXResourceWriter resourceWriter = new ResXResourceWriter(p); IDictionaryEnumerator ids = reader.GetEnumerator(); foreach (DictionaryEntry ds in reader) { //Write (with read to keep xml file order) ResXDataNode dataNodes = (ResXDataNode)ds.Value; //resourceWriter.AddResource(d.Key.ToString(), val); resourceWriter.AddResource(dataNodes); } foreach (ResXDataNode v in list) { resourceWriter.AddResource(v); } //Write to file resourceWriter.Generate(); resourceWriter.Close(); } } }
更新后: