简体   繁体   English

如何在类库项目中引用xml文件

[英]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.

相关问题 如何在项目中引用Aspnet类库 - How to reference Aspnet class library in a project 如何在类库项目中通过服务引用获取XML格式的wcf响应 - How to get wcf response in XML format which is referenced through service reference in class library project 如何在ASP Net Core项目中添加类库项目的引用 - How to add reference of class library project in asp net core project 如何将 class 库引用包含到 docker 文件中 - how to include class library reference into docker file 如何在类库中引用文件 - How to reference a file inside class library 如何获得对 class 库项目的引用才能工作? - How do I get a reference to a class library project to work? 如何在Visual Studio 2010中引用C#类库项目? - How to reference a C# Class Library project in Visual Studio 2010? 如何将.NET类库的引用添加到vNext项目 - How to add a reference of a .NET class library to a vNext Project C ++ / CLI项目如何引用可移植类库? - How can a C++/CLI project reference a portable class library? 如何在不添加对类库的引用的情况下访问另一个类库中的视图模型和项目模型 - How to access view models and models of project in another class library without adding reference to the class library
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM