WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

关于Embedded Resource的理解

Posted on   WebEnh  阅读(84)  评论(0编辑  收藏  举报

Embedded Resource

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

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

Embedded Resource亦即嵌入式资源文件,和资源一样,通过一些设置后也可以作为程序集的一部分发布。有时候我们不想用资源文件的时候也可以使用嵌入式资源,例如将文件my.xml作为资源文件嵌入的设置方法:

image

通过reflector打开程序集可以看到,my.xml文件已经作为程序集的一部分:

image

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

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

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

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

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

下面是一段参考代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 resource in 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();
       }
演示代码下载
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 
0
0
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-05-27 cshtml 中的 AppState = Context.Application 和 控制器中的 Application 也相等
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多