Tuesday, August 23, 2005

Saving an embedded resource xml file at runtime in C#

I couldn't find a cut & dry solution to this (probably b/c it's too simple for anyone to think they would need an example) so here's how I got an xml file embedded as a resource in a vs2003 project written to the filesystem.

First, you just add an xml file with some default information you want for it to your project and change its build action to Embedded Resource. Then, you find the name of the resource (it can be tricky if you have a few folders) by opening up ildasm and double clicking the MANIFEST node. Using that resource name, you would do something like this:

using System;
using System.IO;
using System.Xml;
using System.Reflection;
string path = Path.Combine(
path = Path.Combine(path, Application.ProductName);
path = Path.Combine(path, subFolder);
path = Path.Combine(path, "fileName.xml");
Assembly thisAssembly = Assembly.GetExecutingAssembly();
Stream rgbxml = thisAssembly.GetManifestResourceStream(
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;