visual-studio 将 XML 文件添加到构建中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2326436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 11:35:32  来源:igfitidea点击:

Adding XML Files to the Build

c#visual-studio

提问by cam

I'm using Visual Studio C# Express and I'm wondering how I would go about adding some XML files and being able to reference them in my code. I added the XML files in a folder under the project, but I'm not sure how I can reference them, and then get them copied to the output folder. Originally, before I added them, I just copied the XML files to the Debug folder for Visual Studio, but then when I compiled/installed a new copy of the program I had coded, I had to manually copy the XML files over.

我正在使用 Visual Studio C# Express,我想知道如何添加一些 XML 文件并能够在我的代码中引用它们。我在项目下的文件夹中添加了 XML 文件,但我不确定如何引用它们,然后将它们复制到输出文件夹中。最初,在添加它们之前,我只是将 XML 文件复制到 Visual Studio 的 Debug 文件夹中,但是当我编译/安装我编码的程序的新副本时,我不得不手动复制 XML 文件。

Is there a way to add XML files to a Visual Studio Project and be able to reference them in the code and then have them copied to the output folder?

有没有办法将 XML 文件添加到 Visual Studio 项目并能够在代码中引用它们,然后将它们复制到输出文件夹?

回答by Michal Ciechan

Right click project, Add Existing Resource, browse and select the file you want to add. Then right click the file and click properties and change "Build Action" to content, and "Copy To Output Directory" to Copy if newer (or copy always if the need be). Then you can access it by using the relative path.

右键单击项目,添加现有资源,浏览并选择要添加的文件。然后右键单击该文件并单击属性并将“构建操作”更改为内容,并将“复制到输出目录”更改为如果更新则复制(或者如果需要,则始终复制)。然后您可以使用相对路径访问它。

I use this for my XML and I can access my content using the following code:

我将它用于我的 XML,我可以使用以下代码访问我的内容:

XmlDocument document = new XmlDocument();
document.Load("Resources/DefaultConfig.xml");

Please note that my DefaultConfig.xml file is inside a "Resoruces" Directory which I created in Visual Studio(this is optional, but it helps me keep my project neat)

请注意,我的 DefaultConfig.xml 文件位于我在 Visual Studio 中创建的“资源”目录中(这是可选的,但它帮助我保持项目整洁)