Question

I would like to access resources with different, but ordered names in order using a for loop. For Example:

class Program
{
    static void Main(string[] args)
    {     
        ExtractImages();
    }

    static void ExtractImages()
    {
        Bitmap bmp;

        for (int i = 0; i < 6; i++)
        {
            // Here I need something like: 
            // bmp = new Bitmap(Properties.Resources.bg + i);

            bmp = new Bitmap(Properties.Resources.bg0); // in order bg0..bg5
            bmp.Save("C:\\Users/Chance Leachman/Desktop/bg" + i + ".bmp");
        }
    }
}

Any ideas? It's basically trying to make a String go to a variable name. Thanks!

Was it helpful?

Solution

You can use ResourceManager.GetObject Method

The GetObject method is used to retrieve non-string resources. These include values that belong to primitive data types such as Int32 or Double, bitmaps (such as a System.Drawing.Bitmap object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type.

var bitmap = Properties.Resources.ResourceManager.GetObject("bg0") as Bitmap;

In for loop:

for (int i = 0; i < 6; i++)
{
   string bitmapName = "bg" + i;
   bmp = Properties.Resources.ResourceManager.GetObject(bitmapName) as Bitmap;
   if(bmp != null)
       bmp.Save("C:\\Users/Chance Leachman/Desktop/bg" + i + ".bmp");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top