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

时间:2011-05-20 22:43:52

标签: c# .net visual-studio

我有一个类库项目。在其中一个类中,我需要访问XML文件。如何在类中引用此文件的路径?该文件位于同一项目的其中一个文件夹中。

2 个答案:

答案 0 :(得分:10)

如果你specify the Xml file to be compiled into your assembly,你可以在运行时使用反射来阅读它。

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

更新

由于X509Certificate2构造函数只接受证书文件或字节数组的文件路径,因此您可能希望使用证书文件的可配置路径,而不是将其嵌入到程序集中。

答案 1 :(得分:3)

使用@Filburt提供的链接:

首先将XML文件的BuildAction更改为Embedded资源。它将使用程序集的根命名空间和文件名添加到程序集中: 例如,如果项目的根命名空间是MyNamespace,则资源可能名为MyNamespace.MyXmlFile.xml

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

您可以使用任意数量的类将流作为构造函数参数。