There is a point to this story, but it has temporarily escaped my mind...
Contact Me MyFaceBook MyLinkedIn MyGitHub MyTwitter

Reading embedded files at runtime

I have class library that contains some XML-files as embedded resources. Reading these files at runtime is very easy. It takes only couple of lines of code.

Let’s assume we have class library MyExamples.TestLibrary where we have XML-file called mappings.xml. When we compile our class library then mappings.xml will be put inside assembly as embedded resource. Here is the code to read this XML-file (you need to import System.IO, System.Reflection and System.XML namespaces).

var fileName = "MyExamples.TestLibrary.mappings.xml";
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream(fileName);
 
if (stream == null)
{
    throw new FileNotFoundException("Cannot find mappings file.", fileName);
}
 
var doc = new XmlDocument();
doc.Load(stream);
 
// Do something cool with embedded XML

Some things to notice. If there is no resource we are asking then stream will be null. No exception will be thrown. Second thing is resource name. We don’t use only file name but also assembly name to locate the resource. If you don’t provide assembly name then resource is not found and resource stream is null.


Peipman, G. (5/30/2009). Reading embedded files at runtime. Retrieved 6/8/2009, from Gunnar Peipman's ASP.NET blog: http://weblogs.asp.net/gunnarpeipman/archive/2009/05/30/reading-embedded-files-at-runtime.aspx

Copyright © 2015 by Julian Easterling. SOME RIGHTS RESERVED.

Creative Commons License
Except where otherwise noted, content on this site is
licensed under a Creative Common Attribution-Share Alike 4.0 International License.


All of the opinions expressed on this website are those of Julian Easterling and
do not represent the views of any of my current and previous clients or employers in any way.

If you notice an error on the site or content that has not been properly attributed, bring
it to my attention using the contact page and I will endeavor to fix it as soon as I can.

I accept no responsibility or liability for any damages incurred by following any of
my advice or by using any of the information on my site or of those sites that I link to.