[英]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.
在其中一个类中,我需要访问XML文件。 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. 如果指定要编译到程序集中的Xml文件,则可以使用反射在运行时读取它。
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. 由于X509Certificate2构造函数只接受证书文件或字节数组的文件路径,因此您可能希望使用证书文件的可配置路径,而不是将其嵌入到程序集中。
Using the link that @Filburt provided: 使用@Filburt提供的链接:
First change the BuildAction of your XML file to Embedded resource. 首先将XML文件的BuildAction更改为Embedded资源。 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
它将使用程序集的根命名空间和文件名添加到程序集中:例如,如果项目的根命名空间是MyNamespace,则资源可能名为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. 您可以使用任意数量的类将流作为构造函数参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.