如何发现嵌入式资源的"路径"?

时间:2020-03-05 18:43:14  来源:igfitidea点击:

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

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

名为" file.png"的文件存储在" Resources"文件夹中(在Visual Studio中),并被标记为嵌入式资源。

该代码失败,并显示以下异常:

Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass

我有相同的代码(在不同的程序集中,加载了不同的资源),可以正常工作。所以我知道这项技术是合理的。我的问题是我最终花了很多时间试图找出正确的路径。如果我可以简单地查询(例如在调试器中)程序集以找到正确的路径,那将节省很多麻烦。

解决方案

回答

我猜课程位于其他名称空间中。解决此问题的规范方法是使用资源类和强类型资源:

ProjectNamespace.Properties.Resources.file

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

回答

这将为我们提供所有资源的字符串数组:

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

回答

我发现自己也忘记了每次都该怎么做,所以我只把我需要的两条单线包装在一个小班里:

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();
    }
}