w128
w128

Reputation: 4928

Resource file (.resx) vs reflection to access an embedded resource

I may be missing something very simple here, but what's the benefit of using reflection to retrieve an embedded resource from the same assembly that contains the resource as opposed to simply retrieving it via an .resx file? I see this a lot but don't get it - is there a reason to use Assembly.GetExecutingAssembly().GetManifestResourceStream(resource) compared to resx file Resources.resource? Even Microsoft does it: How to embed and access resources.

What I mean exactly: suppose I have an assembly MyAssembly that contains an embedded resource Config.xml. The assembly has MyClass that implements a method that returns said resource as a string:

public string GetConfigXML() // returns the content of Config.xml as a string

Often, I see this implemented like this, using reflection to retrieve the resource:

public string GetConfigXML()
{
    Stream xmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyAssembly.Config.xml"); 
    string xml = GetStringFromStream(xmlStream);
    return xml;
}

Why use GetManifestResourceStream() when you can:

  1. add a resource file (Resource.resx) to the MyAssembly project in Visual Studio;
  2. add Config.xml to the resource's 'Files';
  3. get the content of Config.xml in a much simpler way: string xml = Resource.Config;

I don't know how Visual Studio handles .resx files internally, but I doubt it simply copies the resource into the .resx file (in which case you'd end up with duplicated resources). I assume it doesn't use reflection internally either, so why not simply use .resx files in situations like this, which seems much more performance-friendly to me?

Upvotes: 6

Views: 3789

Answers (1)

Hans Passant
Hans Passant

Reputation: 941455

but what's the benefit of using reflection to retrieve an embedded resource

The common benefit that's behind any reason to convert data from one format to another. Speed, speed, speed and convenience.

XML is a pretty decent format to keep your resources stored in. You'll have a very good guarantee that you can still retrieve the original resource 10 years from now when the original got lost in the fog of time and a couple of machine changes without good backups. But it is quite a sucky format to have to read from, XML is very verbose and locating a fragment requires reading from the start of the file.

Problems that disappear when Resgen.exe compiles the .xml file into a .resource file. A binary format that's fit to be linked into your assembly metadata and contains the original bytes in the resource. And is directly mapped into memory when your assembly is loaded, no need to find another file and open it, read it and convert the data. Big difference.

Do use the Resource Designer to avoid having to use GetManifestResourceStream() directly. Yet more convenience.

Upvotes: 4

Related Questions