简体   繁体   中英

How to reference xml file in Class library project

I have a class library project. In one of the classes I need to access an XML file. How do I reference the path to this file in a class? The file is located in one of the folders of the same project.

If you specify the Xml file to be compiled into your assembly you can read it at runtime using reflection.

Assembly asm = Assembly.GetExecutingAssembly();
XmlDocument doc = new XmlDocument();
XmlTextReader reader = new XmlTextReader(asm.GetManifestResourceStream("MyNamespace.MyXmlFile.xml"));
doc.Load(reader);

Update

Since the X509Certificate2 constructor will only accept a file path to your certificate file or a byte array you might want to use a configurable path to your certificate file instead of embedding it into your assembly.

Using the link that @Filburt provided:

First change the BuildAction of your XML file to Embedded resource. It will be added to your assembly with the root namespace of your assembly and the filename: For example, if the root namespace of your project is MyNamespace, a resource might be named MyNamespace.MyXmlFile.xml

   Assembly _assembly;
   StreamReader _textStreamReader;
   _assembly = Assembly.GetExecutingAssembly();
   _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("MyNameSpace.MyXmlFile.xml"));

You could use any number of classes that take a stream as a constructor parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM