我将PNG存储为程序集中的嵌入式资源.在同一个程序集中,我有一些像这样的代码:
Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");
名为"file.png"的文件存储在"Resources"文件夹中(在Visual Studio中),并标记为嵌入式资源.
代码失败,异常说:
在MyNamespace.MyClass类中找不到资源MyNamespace.Resources.file.png
我有相同的代码(在不同的程序集中,加载不同的资源)工作.所以我知道这种技术很合理.我的问题是我最终花了很多时间试图弄清楚正确的路径是什么.如果我可以简单地查询(例如在调试器中)程序集以找到正确的路径,那将为我节省大量的麻烦.
这将获得所有资源的字符串数组:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
我发现自己每次都忘记了如何做到这一点,所以我只需要在一个小课程中包装我需要的两个单行:
public class Utility { ////// Takes the full name of a resource and loads it in to a stream. /// /// Assuming an embedded resource is a file /// called info.png and is located in a folder called Resources, it /// will be compiled in to the assembly with this fully qualified /// name: Full.Assembly.Name.Resources.info.png. That is the string /// that you should pass to this method. ///public static Stream GetEmbeddedResourceStream(string resourceName) { return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); } /// /// Get the list of all emdedded resources in the assembly. /// ///An array of fully qualified resource names public static string[] GetEmbeddedResourceNames() { return Assembly.GetExecutingAssembly().GetManifestResourceNames(); } }
我猜你的类在不同的命名空间中.解决此问题的规范方法是使用资源类和强类型资源:
ProjectNamespace.Properties.Resources.file
使用IDE的资源管理器添加资源.
我使用以下方法来获取嵌入资源:
protected static Stream GetResourceStream(string resourcePath) { Assembly assembly = Assembly.GetExecutingAssembly(); ListresourceNames = new List (assembly.GetManifestResourceNames()); resourcePath = resourcePath.Replace(@"/", "."); resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath)); if (resourcePath == null) throw new FileNotFoundException("Resource not found"); return assembly.GetManifestResourceStream(resourcePath); }
然后我用项目中的路径调用它:
GetResourceStream(@"DirectoryPathInLibrary/Filename")