0

If I have some resources, eg card1.png, card2.png, etc, I want to them load them into a picBox, but only load the correct image eg, something like

int cardNum = rn.Next(0,cardMax);
picCard.Image = Properties.Resources."card"+cardNum+".png";

Obviously that doesn't work, but how would I do what I am trying to do (load the correct resource after building the resource name into a string)

  • 1
    Possible duplicate of [How to get Name by string Value from a .NET resource (RESX) file](http://stackoverflow.com/questions/16361685/how-to-get-name-by-string-value-from-a-net-resource-resx-file) – Andrey Korneyev Jun 29 '16 at 08:22
  • 1
    @AndyKorneyev That's about finding a resource's key by matching its content, not loading by name. – Richard Jun 29 '16 at 08:26
  • Open Resources.Designer.resx and you see exactly how they are looked up by string name. – Nyerguds Jun 29 '16 at 08:27
  • You probably need [`Assembly.GetManifestResourceStream`](https://msdn.microsoft.com/en-us/library/xc4235zt(v=vs.110).aspx). – Richard Jun 29 '16 at 08:28
  • Note that when adding something to the resources, the extension is generally stripped off. While it's technically allowed, the dot character is deemed a "bad character" in resource names. – Nyerguds Jun 29 '16 at 08:30
  • Derp. I meant `Resources.Designer.cs`, of course. Just missed the edit window to correct it. – Nyerguds Jun 29 '16 at 08:33

2 Answers2

2

Instead of the generated properties in the Resources class use the ResourceManager directly:

string resName = $"card{cardNum}.png"; // Check the correct name in the .resx file. By using the wizards the extension is omitted, for example.
picCard.Image = (Image)Properties.Resources.ResourceManager.GetObject(resName);
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65
0

Try using:

var rm = new System.Resources.ResourceManager(((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()).GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()));
Image img = (Bitmap)rm.GetObject("resourcesimagename.jpg");