Embedded Resource
.NET中使用外部资源时常用的方式都是使用资源文件,作为程序集的一部分发布。资源文件的读取也比较方便,字符串、图片和任何二进制数据,包括任何类型的文件都可以作为资源的项。
使用资源文件时VS也会自动生成相应的方法来获取资源,用xml编辑器打开后缀.resx的文件,可以看到资源文件是用xml方式存储的。
Embedded Resource亦即嵌入式资源文件,和资源一样,通过一些设置后也可以作为程序集的一部分发布。有时候我们不想用资源文件的时候也可以使用嵌入式资源,例如将文件my.xml作为资源文件嵌入的设置方法:
通过reflector打开程序集可以看到,my.xml文件已经作为程序集的一部分:
其嵌入的资源文件命名规则为:程序集+文件夹名(如果存在)+文件名(含后缀名)。
文件属性中“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(); } |
本博客Android APP 下载 |
![]() |
支持我们就给我们点打赏 |
![]() |
支付宝打赏 支付宝扫一扫二维码 |
![]() |
微信打赏 微信扫一扫二维码 |
![]() |
如果想下次快速找到我,记得点下面的关注哦!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2019-05-27 cshtml 中的 AppState = Context.Application 和 控制器中的 Application 也相等