如何发现embedded式资源的“path”?

我将PNG作为embedded式资源存储在程序集中。 从同一个程序集中,我有这样的代码:

Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png"); 

名为“file.png”的文件存储在“Resources”文件夹(Visual Studio中)中,并被标记为embedded资源。

代码失败,例外说:

资源MyNamespace.Resources.file.png不能在类MyNamespace.MyClass中find

我有相同的代码(在不同的程序集中,加载不同的资源),它的工作原理。 所以我知道这个技术是很好的。 我的问题是我花了很多时间去弄清楚正确的道路是什么。 如果我可以简单地查询(例如在debugging器中)程序集以find正确的path,这将为我节省一大笔头痛的负担。

这会得到你所有资源的string数组:

 System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); 

我发现自己每次都忘记如何做到这一点,所以我只是把我需要的两个单行包装在一个小class里:

 public class Utility { /// <summary> /// Takes the full name of a resource and loads it in to a stream. /// </summary> /// <param name="resourceName">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.</param> /// <returns></returns> public static Stream GetEmbeddedResourceStream(string resourceName) { return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); } /// <summary> /// Get the list of all emdedded resources in the assembly. /// </summary> /// <returns>An array of fully qualified resource names</returns> public static string[] GetEmbeddedResourceNames() { return Assembly.GetExecutingAssembly().GetManifestResourceNames(); } } 

我猜你的class级在不同的命名空间。 解决这个问题的标准方法是使用资源类和强types资源:

 ProjectNamespace.Properties.Resources.file 

使用IDE的资源pipe理器添加资源。

我使用以下方法来获取embedded的资源:

  protected static Stream GetResourceStream(string resourcePath) { Assembly assembly = Assembly.GetExecutingAssembly(); List<string> resourceNames = new List<string>(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); } 

然后我在项目中调用这个path:

 GetResourceStream(@"DirectoryPathInLibrary/Filename") 

资源的名称是名称空间加上文件path的“伪”名称空间。 “伪”名称空间由子文件夹结构使用\(反斜杠)而不是。 (点)。

 public static Stream GetResourceFileStream(String nameSpace, String filePath) { String pseduoName = filePath.Replace('\\', '.'); Assembly assembly = Assembly.GetExecutingAssembly(); return assembly.GetManifestResourceStream(nameSpace + "." + pseduoName); } 

以下电话:

 GetResourceFileStream("my.namespace", "resources\\xml\\my.xml") 

将返回位于名称空间中的文件夹结构资源\ xml中的my.xmlstream:my.namespace。