关于Embedded Resource(嵌入式资源)的理解 分类: .NET 2014-07-22 11:23 767人阅读 评论(0) 收藏

关于Embedded Resource的理解

2012-02-26 22:28 by Ecin, 471 阅读, 0 评论, 收藏编辑

Embedded Resource

.NET中使用外部资源时经常使用的方式都是使用资源文件,做为程序集的一部分发布。资源文件的读取也比较方便,字符串、图片和任何二进制数据,包括任何类型的文件均可以做为资源的项。html

使用资源文件时VS也会自动生成相应的方法来获取资源,用xml编辑器打开后缀.resx的文件,能够看到资源文件是用xml方式存储的。编辑器

Embedded Resource亦即嵌入式资源文件,和资源同样,经过一些设置后也能够做为程序集的一部分发布。有时候咱们不想用资源文件的时候也能够使用嵌入式资源,例如将文件my.xml做为资源文件嵌入的设置方法:函数

image

经过reflector打开程序集能够看到,my.xml文件已经做为程序集的一部分:post

image

其嵌入的资源文件命名规则为:程序集+文件夹名(若是存在)+文件名(含后缀名)。this

文件属性中“Copy to OutPut Directory”选定嵌入资源文件的的输出方式。url

关于资源文件/嵌入式资源文件的读取

读取资源文件/嵌入式资源文件的通常方式为先加载资源所在的程序集,利用反射获取程序集中的外部文件数据:spa

  • 读取资源文件名使用:string[] Assembly.GetManifestResourceNames(). 返回的是全部程序集资源清单文件
  • 资源文件的读取使用System.Resources.ResourceManager类,构造函数签名:public ResourceManager(string baseName, Assembly assembly).
  • 嵌入式资源文件的读取使用Assembly.GetManifestResourceStream(string name)

下面是一段参考代码:
code

static void Main(string[] args)
{
   Assembly assembly = Assembly.Load("ResourceSample");
   string content = string.Empty;

   //GetManifestResourceNames:this method used to find all resource name.
   foreach (string resourcein assembly.GetManifestResourceNames())
   {
       Console.WriteLine("Manifest:{0}", resource);
       if (resource.IndexOf(".Resource1") > 0)
       {
           ResourceManager manager = new ResourceManager("ResourceSample.Resource1", assembly);
           //read specified string 
           Console.WriteLine("resource key:mytest,value:{0}",manager.GetString("mytest"));
       }
       else
       {
           //read Embedded  resource
           using (Stream stream = assembly.GetManifestResourceStream(resource))
           {
               using (StreamReader reader = new StreamReader(stream))
               {
                   Console.WriteLine(reader.ReadToEnd());
               }
           }
       }
   }
    
   Console.ReadKey();
}


演示代码 下载

本文版权归做者和博客园共有,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文链接,不然保留追究法律责任的权利。orm


原文地址:http://www.cnblogs.com/ecin/archive/2012/02/26/2369139.htmlxml

相关文章
相关标签/搜索