从项目目录加载XML文件

时间:2023-02-06 12:39:50

I have in my WPF project an "assets" folder by the fonts, images and XML files. How can I read XML files from the project directory using C#? Tried it on the Assembly, but the file can not be found. About XAML can very easily download images from that folder.

我在我的WPF项目中有一个由字体,图像和XML文件组成的“assets”文件夹。如何使用C#从项目目录中读取XML文件?在大会上尝试过,但无法找到该文件。关于XAML可以非常轻松地从该文件夹下载图像。

When I use the follow string, the file can't be found. How can I load my XML file from the project directory?

当我使用跟随字符串时,无法找到该文件。如何从项目目录加载我的XML文件?

string stream = "pack://application:,,,/ReferencedAssembly;component/assets/myxml.xml";

Thanks in advance for any help.

在此先感谢您的帮助。

3 个解决方案

#1


5  

One solution to load your file, using Linq to Xml, is:

使用Linq到Xml加载文件的一种解决方案是:

XDocument myxml = XDocument.Load(@"assets\myxml.xml");

#2


0  

I've got a very similar issue, I was not able to load file from folder in project structure. All settings were correct, but still it was returning IO error.

我有一个非常类似的问题,我无法从项目结构中的文件夹加载文件。所有设置都是正确的,但仍然是返回IO错误。

All answers abow are probably correct - but in my case it still want to load file. There is a need to change one property more:

所有答案可能都是正确的 - 但在我的情况下,它仍然想要加载文件。需要更多地更改一个属性:

  • Build Action = Embedded Resource
  • 构建动作=嵌入式资源
  • Copy to Output Directory = Copy always
  • 复制到输出目录=始终复制

Without setting it as "Embedded Resource" it was not reachable from my program. After change it is working.

如果不将其设置为“嵌入式资源”,则无法从我的程序中访问它。改变后它正在运作。

#3


0  

After search in deep and deep web:

在深度和深度网页搜索后:

Set the "Build Action" property for the XML file to "Embedded Resource".

将XML文件的“Build Action”属性设置为“Embedded Resource”。

And use:

并使用:

XDocument xdoc = XDocument.Load(this.GetType().Assembly.GetManifestResourceStream("ProjectName.FolderName.XmlArchive.xml"));

=D

= d

#1


5  

One solution to load your file, using Linq to Xml, is:

使用Linq到Xml加载文件的一种解决方案是:

XDocument myxml = XDocument.Load(@"assets\myxml.xml");

#2


0  

I've got a very similar issue, I was not able to load file from folder in project structure. All settings were correct, but still it was returning IO error.

我有一个非常类似的问题,我无法从项目结构中的文件夹加载文件。所有设置都是正确的,但仍然是返回IO错误。

All answers abow are probably correct - but in my case it still want to load file. There is a need to change one property more:

所有答案可能都是正确的 - 但在我的情况下,它仍然想要加载文件。需要更多地更改一个属性:

  • Build Action = Embedded Resource
  • 构建动作=嵌入式资源
  • Copy to Output Directory = Copy always
  • 复制到输出目录=始终复制

Without setting it as "Embedded Resource" it was not reachable from my program. After change it is working.

如果不将其设置为“嵌入式资源”,则无法从我的程序中访问它。改变后它正在运作。

#3


0  

After search in deep and deep web:

在深度和深度网页搜索后:

Set the "Build Action" property for the XML file to "Embedded Resource".

将XML文件的“Build Action”属性设置为“Embedded Resource”。

And use:

并使用:

XDocument xdoc = XDocument.Load(this.GetType().Assembly.GetManifestResourceStream("ProjectName.FolderName.XmlArchive.xml"));

=D

= d