我有一个程序,在"Icons"文件夹中包含许多图标(包含在Build Action = Resource的项目中).
在XAML中,我可以使用诸如<Image Source="../Icons/name.png"/>(".."之类的代码访问这些图标,因为XAML位于不同的子文件夹中); 但是我想在同一个项目中的某些WinForms代码中使用相同的图像.不幸,
GetType().Assembly.GetManifestResourceStream("Icons/name.png");
Run Code Online (Sandbox Code Playgroud)
回归null和
GetType().Assembly.GetManifestResourceNames()
Run Code Online (Sandbox Code Playgroud)
只列出了一堆*.resources文件(每个文件一个.resx,一个名为*.g.resources).那么我该如何获得图像流呢?
我认为,因为我直接将图像包含在我的项目中,我可以直接阅读它们.但是由于Jack的回答,我能够发现它们隐藏在程序集内部名为"ProgramName.g.resources"的"资源文件"中.要读取图像,必须先加载资源文件,然后在资源文件中搜索图像文件.
ResourceSet.GetObject区分大小写,但由于某种原因,图像路径和文件名被转换为小写,所以我调用ToLowerInvariant路径名.这是我的解决方案:
private Stream GetGlobalResourceByPath(Assembly assembly, string path)
{
string name = assembly.GetManifestResourceNames().Where(n => n.EndsWith(".g.resources")).First();
Stream outerStream = assembly.GetManifestResourceStream(name);
ResourceSet resources = new ResourceSet(outerStream);
return resources.GetObject(path.ToLowerInvariant()) as UnmanagedMemoryStream;
}
Run Code Online (Sandbox Code Playgroud)
我不确定构建一个有多昂贵ResourceSet.如果它很昂贵,并且您想要检索多个资源,那么您应该缓存并重新使用该ResourceSet对象.
如果你知道为什么图像最终会出现在*.g.resources文件中,请留言.Visual Studio是否选择了此名称?理论上可以将图像直接放在装配体中,还是装配体只包含"ResourceSets"?