Search code examples
c#embedded-resource

How to load images from resources with GetManifestResourceStream?


How to load images from Resources, please? Some of my images are located inside a folder.

My image is saved as Resource (cf. Build Action). I don't use a .resx file.

I'm able to retrieve the list of all my resources with the help of this function:

public static string[] GetResourceNames()
{
    var asm = Assembly.GetEntryAssembly();
    string resName = asm.GetName().Name + ".g.resources";
    using (var stream = asm.GetManifestResourceStream(resName))
    using (var reader = new System.Resources.ResourceReader(stream))
    {
        return reader.Cast<DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
    }
}

but I'm not able to load the resource (an image in my case).

Here are my tests:

string[] resourceNames = GetResourceNames();

Assembly assembly = Assembly.GetExecutingAssembly();
string projectName = assembly.GetName().Name;

string gresourceName = assembly.GetName().Name + ".g.resources";
//string gresourceName = assembly.GetName().Name + ".Properties.Resources";
var rm = new System.Resources.ResourceManager(gresourceName, typeof(Resources).Assembly);

var list = resourceNames.OrderBy(q => q).ToList(); //sort

//get all png images
foreach (string resourceName in list)
{
    if (resourceName.EndsWith(".png"))
    {
        try
        {
            Console.WriteLine(resourceName.ToString());

            //var test =  (Bitmap)rm.GetObject(resourceName);

            Stream imageStream = assembly.GetManifestResourceStream(gresourceName + "." + resourceName);
        }
        catch (Exception ex) {
            Console.WriteLine("EXCEPTION: " + ex.Message);
        }
    }
}

In my case: assembly = "VisualStudioTest" resourceName = "testImages/add_32x32.png"

I've tried all combinations without success. By example: assembly.GetManifestResourceStream("VisualStudioTest.Properties.Resources.testImages.add_32x32.png") assembly.GetManifestResourceStream("VisualStudioTest.g.resources.testImages.add_32x32.png")


Solution

  • According to Build actions page, Resource Build Type is for WPF projects. Are you working on a WPF project?

    Using Embedded Resources instead would look like this:

    var asm = Assembly.GetEntryAssembly();
    foreach (string resourceName in asm.GetManifestResourceNames())
    {
        if (resourceName.EndsWith(".png"))
        {
            try
            {
                Console.WriteLine(resourceName.ToString());
                Stream imageStream = assembly.GetManifestResourceStream(resourceName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("EXCEPTION: " + ex.Message);
            }
        }
    }