Search code examples
.netxmlembedded-resourcexmldocument

Handling XML embedded in .NET assembly vs. external file: what's wrong with my code?


Please tell me why these 2 don't give me the same XmlDocument object.

  1. I can successfully load an external xml file using this code and successfully process the xml file:

    var xElem = XElement.Load("Products.xml");
    
  2. Now I embed the xml file as embedded resources in the assembly instead:

    var assembly = Assembly.GetExecutingAssembly();
    var stream = assembly.GetManifestResourceStream(this.GetType(), "AppNameSpace.Products.xml");
    var xElem= new XmlDocument();
    xElem.Load(stream);
    

Aren't the 2 xElem's supposed to be the same? Both XmlDocument containing the same info in Products.xml?

What did I do wrong? Thanks.

If I want to get the same xElem as in scenario 1, what must I do in scenario 2?


Solution

  • Build your XML file as a resource i.e. set "Build Action" to "Embeded Resource" in your Properties window when you add the file to the project.

    See the following links

    Check if your image exists in the resources with this

    thisExe = System.Reflection.Assembly.GetExecutingAssembly();
    string [] resources = thisExe.GetManifestResourceNames();
    

    Edit: Ok I just checked, you need to set the "Build Action" to "Embeded Resource". Setting it to "Resource" will not work. Do this, and check for the name of the resource with the above code. I'm sure it will work.