Reading embedded files at runtime with C#

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);

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.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    One thought on “Reading embedded files at runtime with C#

    • June 8, 2009 at 12:59 pm
      Permalink

      My favorite one liner to get a schema from an embedded resource:

      this.task.ReadXmlSchema(new XmlTextReader(new StringReader(Resources.Task)));

    Leave a Reply

    Your email address will not be published. Required fields are marked *