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); }
A couple of things to note about this: it's for a WinForms application, so I can use the Application class to get things in AssemblyInfo.cs (like ProductName, CompanyName). Also, you could probably do this anywhere but I chose to put a lot of my default configuration under the user's ApplicationData folder, where most users (can't say for sure about the guest account since that's been disabled here for a long time) have authority to write.