.NET 下各种Resource的读取方式
1) Embedded Resource (Build Action 设置为 Embedded Resource) 在运行时使用GetManifestResourceStream读取
Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.warning.png"));
2) Resource (Build Action 设置为 Resource) 在运行时使用 Resource Manager读取
ResourceManager rm = new ResourceManager("WindowsFormsApplication1.g", typeof(Form1).Assembly);
Image warImg = null;
ResourceSet rs= rm.GetResourceSet(new System.Globalization.CultureInfo("en"),true,true);
foreach (DictionaryEntry item in rs)
{
Console.WriteLine(item.Key.ToString());
warImg = Bitmap.FromStream(item.Value as Stream);
}
3) 如果是直接添加图片到.Resx资源文件中,在运行时使用Resource Manager读取, 但读取方式有不同
ResourceManager rm = new ResourceManager("WindowsFormsApplication1.Properties.Resources", typeof(Form1).Assembly);
Bitmap warnImg = rm.GetObject("warning") as Bitmap;
以上是WinForm 和 WPF下的情况,在ASP.NET下还有另外一种嵌入资源方式,通过WebResourceAttribute, NOTE: 这里的image的build action必须是Embedded Resource.
添加 assembly attribute:
[assembly: WebResourceAttribute("ServerControl1.images.component.gif", "image/gif")]
客户端读取:
string imgURL = Page.ClientScript.GetWebResourceUrl(typeof(ServerControl1), ("ServerControl1.images.component.gif");