karthik
karthik

Reputation: 4741

how to embed an xml file to a resource file

i want to embed a xml file to a resource file in my project,whenever i need the file i must get it from resource and use it,how to do this and i want to modify the contents of the xml file depending upon my requirements.how to do this

Upvotes: 5

Views: 8747

Answers (2)

sixdiamants
sixdiamants

Reputation: 131

In Visual Studio (2022) you may want to use an existing, or create a new resources.resx or any other appropriate resx file.

In VS project explorer ...

  1. double clicking the resource file will open the resource designer.
  2. from the menu (over the designer, but not very visible), choose Add resource,
  3. add existing fileName.xml. The designer automagically produces a code-behind accessor.
  4. read the xml resource, using said accessor, like so

XDocument myXml = XDocument.Parse(myNamespace.Properties.Resources.LdPropertyTemplate);

Tweak the path to the resource "myNamespace.Properties" to your project setup.

Upvotes: 0

user116587
user116587

Reputation:

If you add the XML file to a Visual Studio project and, in the Property window for it, select Build Action: Embedded resource, the file will be embedded into the build output artifact for that project.

To access it from code, use something like:

string resourceName = "Namespace.Prefix.FileName.xml";
Assembly someAssembly = LoadYourAssemblyContainingTheResource();
XmlDocument xml = new XmlDocument();
using (Stream resourceStream = someAssembly.GetManifestResourceStream(resourceName))
{
    xml.Load(resourceStream);
}
// The embedded XML resource is now available in: xml

If the resource you're loading is embedded in your own assembly, you can do something like Assembly.GetExecutingAssembly() to achieve what I listed as LoadYourAssemblyContainingTheResource() above, or possibly typeof(SomeTypeInYourResourceAssembly).Assembly

It's unclear what you mean by "want to modify the contents" - you cannot modify the resource inside the assembly at run-time, but whenever you change the XML file and recompile, the new version will be embedded.

Upvotes: 13

Related Questions