tags:

views:

362

answers:

5

How can I read from an embedded XML file - an XML file that is part of a c# project? I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see.

Any idea?

+2  A: 
  1. Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.)

  2. Set the "Build Action" property for the XML file to "Embedded Resource".

  3. Use the following code to retrieve the file contents at runtime:

    public string GetResourceTextFile(string filename)
    {
        string result = string.Empty;
    
    
    
    using (Stream stream = this.GetType().Assembly.GetManifestResourceStream("assembly.folder."+filename))
    {
        using (StreamReader sr = new StreamReader(stream))
        {
            result = sr.ReadToEnd();
        }
    }
    
    
    return result;
    
    }

Whenever you want to read the file contents, just use

 string fileContents = GetResourceTextFile("myXmlDoc.xml");
David Lively
+1  A: 

Set the Build Action to Embedded Resource, then write the following:

using (Stream stream = typeof(MyClass).Assembly.GetManifestResourceStream("MyNameSpace.Something.xml")) {
    //Read the stream
}
SLaks
A: 
  1. Add the file to the project.
  2. Set the "Build Action" property to "Embedded Resource".
  3. Access it this way: GetType().Module.Assembly.GetManifestResourceStream("namespace.folder.file.ext")

Notice that the resource name string is the name of the file, including extension, preceded by the default namespace of the project. If the resource is inside a folder, you also have to include it in the string.

(from http://www.dotnet247.com/247reference/msgs/1/5704.aspx, but I used it pesonally)

Grzenio
A: 

You can also add the XML file as a Resource and then address it's contents with Resources.YourXMLFilesResourceName (as a string, i.e. using a StringReader).

Markus
+1  A: 

You can use Reflector (free from http://www.red-gate.com/products/reflector/) to find the path to the embedded xml file.

Then, it's just a matter of

        Assembly a = typeof(Assemmbly.Namespace.Class).Assembly;

        Stream s = a.GetManifestResourceStream("Assembly.Namespace.Path.To.File.xml");
        XmlDocument mappingFile = new XmlDocument();
        mappingFile.Load(s);
        s.Close();
Jamie
You should close the stream. Also, writing `typeof(SomeType)`.Assembly` will be _substantially_ faster.
SLaks
Done. Great points.
Jamie
You should close the stream using a `using` statement.
SLaks