C# 实现从程序集中抽取内嵌资源文件
#region 字段 常量 private const string PATTERN_TEMPLATE = "*.cmt"; /// <summary> /// 模板文件后缀名 /// </summary> private const string EXTEN_NAME_TEMPLATE = ".cmt"; #endregion
从嵌入的资源文件读取文件,并释放到指定目录:
1 //从资源文件释放模板文件 2 Assembly assembly = System.Reflection.Assembly.GetEntryAssembly(); 3 4 string[] resNames = assembly.GetManifestResourceNames(); //列出所有资源名称 5 //string fileName = assembly.GetName().Name + ".Resources.Rc1.grf"; 6 7 foreach (var itemResFileName in resNames) 8 { 9 if (itemResFileName.EndsWith(EXTEN_NAME_TEMPLATE)) 10 { 11 var arr_Names = itemResFileName.Split('.'); 12 string fileName = string.Concat(arr_Names[arr_Names.Length - 2], EXTEN_NAME_TEMPLATE); 13 string outPutFileFullName = Path.Combine(templateDir, fileName); 14 if (File.Exists(outPutFileFullName)) 15 { 16 continue; 17 } 18 19 FileUtility.ExtractResFile(assembly, itemResFileName, outPutFileFullName); 20 } 21 }
1 /// <summary> 2 /// 文件辅助类 3 /// </summary> 4 public class FileUtility 5 { 6 7 8 /// <summary> 9 /// 从当前执行程序集资源文件中抽取资源文件 10 /// </summary> 11 /// <param name="resFileName">资源文件名称(资源文件名称必须包含目录,目录间用“.”隔开,最外层是项目默认命名空间)</param> 12 /// <param name="outputFile">输出文件</param> 13 public static void ExtractResFile(string resFileName, string outputFile) 14 { 15 Assembly asm = Assembly.GetExecutingAssembly(); //读取嵌入式资源 16 ExtractResFile(asm, resFileName, outputFile); 17 } 18 19 20 /// <summary> 21 /// 从指定的程序集中解压文件 22 /// </summary> 23 /// <param name="asm">程序集</param> 24 /// <param name="resFileName">资源文件名称(资源文件名称必须包含目录,目录间用“.”隔开,最外层是项目默认命名空间))</param> 25 /// <param name="outputFile">输出文件</param> 26 public static void ExtractResFile(Assembly asm, string resFileName, string outputFile) 27 { 28 if (asm == null) 29 { 30 return; 31 } 32 33 34 /// Assembly asm = Assembly.GetExecutingAssembly(); //读取嵌入式资源 35 using (var inStream = new BufferedStream(asm.GetManifestResourceStream(resFileName))) 36 { 37 using (var outStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) 38 { 39 byte[] buffer = new byte[1024]; 40 int length; 41 42 while ((length = inStream.Read(buffer, 0, buffer.Length)) > 0) 43 { 44 outStream.Write(buffer, 0, length); 45 } 46 outStream.Flush(); 47 } 48 49 50 } 51 } 52 53 54 55 56 57 }