Resource file (.resx) against reflection to access the embedded resource

I may miss something very simple here, but what is the use of using reflection to extract an embedded resource from the same assembly that contains the resource , rather than just extracting it through a .resx file? I see this a lot, but I don’t understand - is there a reason to use Assembly.GetExecutingAssembly().GetManifestResourceStream(resource) compared to the resx Resources.resource file? Even Microsoft does this: How to implement and access resources .

What I mean exactly: suppose I have a MyAssembly assembly that contains the Config.xml built-in resource. The collection has MyClass , which implements a method that returns the specified resource as a string:

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

Often I see that this is implemented like this, using reflection to retrieve a resource:

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

Why use GetManifestResourceStream() if you can:

  • Add a resource file ( Resource.resx ) to the MyAssembly project in Visual Studio;
  • Add Config.xml to the Files resource;
  • getting the contents of Config.xml much simpler: string xml = Resource.Config;

I do not know how Visual Studio processes .resx files internally, but I doubt that it simply copies the resource to the .resx file (in this case, you will get duplicated resources). I assume that it also does not use reflection inside, so why not just use .resx files in situations that seem more convenient to me?

+6
source share
1 answer

but what is the advantage of using reflection to extract an embedded resource

The overall benefit behind any reason for converting data from one format to another. Speed, speed, speed and convenience.

XML is a pretty decent format for storing your resources. You will have a very good guarantee that you can still get the original resource after 10 years, when the original was lost in the fog of time and a couple of machine changes without good backups. But this is a rather complicated format to read, XML is very detailed, and reading a fragment requires reading from the very beginning of the file.

Problems that disappear when Resgen.exe compiles an XML file into a .resource file. A binary format that is suitable for connecting to your assembly metadata and contains the source bytes in the resource. And it is directly displayed in memory when loading the assembly, there is no need to find another file and open it, read and convert data. Big difference.

Use the resource constructor to avoid using GetManifestResourceStream () directly. Even more convenience.

+3
source

All Articles