Freigeben über


Why does retrieving resources have to be so difficult? Oops, it's not...

Loading embedded resources at runtime has always mystified me.  Should I use the ComponentResourceManager class?  Should I try to find the ResourceStream in the assembly?  And what's the correct name to use to identify it?  Is it simply the file name? Or is it the name of the default namespace plus the filename?  Or do I need to specify the assembly name and the filename?  And I don't do it often enough to remember how I did it the last time.  Arrrrrggggghhh!

Well, I finally realized that I don't need to jump through all of those hoops: any resource that is added to the Resources.resx file can be accessed by name through Properties.Resources.  For instance, if I add an icon named Hiho.ico to Resources.resx,  I can reference it via Properties.Resources.Hiho.  No muss, no fuss!

A couple of things are worth noting here.  First, the name that matters is the resource identifier in Resource.resx, not the file name.  By default, Visual Studio uses the base file name of the resource as the resource identifier.  However, the resource identifier and the file name need not match.  For instance, if there is already a resource identifier with that name, Visual Studio will create a new resource identifier by appending a digit to the base file name.  Or you might have a co-worker with a perverse sense of humor who decides to rename all of the resources with the names of Disney characters.

The second item of interest (to me, at least) is a bit more esoteric: the resources aren't listed in the assembly manifest.  If you simply add the Hiho.ico file to your project and mark it as an embedded resource, you'll see an entry in the manifest like this after you build:

    mresource public Foo.Resources.Hiho.ico

However, if you add it to the Resources.resx file without including it as an Embedded object, this line won't appear in the manifest.  If you know why this is, please leave me a comment.

CheersDan

 

DISCLAIMER: The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer.