Can I convert a string to a resource location in C

2019-05-29 01:40发布

问题:

Ok, beginner here just getting into learning programming, trying to make something in C#. Essentially, I have a string..

string resourcename = "example"

Conveniently enough, I also have a resource called example.jpg.. Now I'm trying to set my backgroundimage to example.jpg, using the string 'resourcename' instead of the actual filename.. Normally I'd do this:

this.BackgroundImage = namespace.Properties.Resources.example;

So now I'd like to do something like

this.BackgroundImage = namespace.Properties.Resources.resourcename;

Obviously, it doesn't recognize that because it's a string, so is there any way I can incorporate a string into the resource location?

Thanks! : D

回答1:

Combining the ideas from the two previous answers, you might try something like this:

BackgroundImage = (Image)Properties.Resources.ResourceManager.GetObject(resourcename));


回答2:

string resourcename = "example"
this.BackgroundImage = Image.FromFile(@"C:\Users\m\Documents\...\" + resourcename + ".jpg" ) ;