Pages

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(
Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData),
Application.CompanyName);
path = Path.Combine(path, Application.ProductName);
path = Path.Combine(path, subFolder);
path = Path.Combine(path, "fileName.xml");
if(!File.Exists(path)){
Assembly thisAssembly = Assembly.GetExecutingAssembly();
Stream rgbxml = thisAssembly.GetManifestResourceStream(
"YourNamespace.fileName.xml");
XmlDocument doc = new XmlDocument();
doc.Load(rgbxml);
doc.PreserveWhitespace = true;
doc.Save(path);
}