DirectoryNotFoundException C#将XML文件加载到控制台应用程序时出错

Big*_*bie 1 c#

我是C#的新手,并尝试解析XML文档,但我不断收到错误消息,找不到目录

显然\bin\Debug,程序启动时我的xml文件和数据文件夹没有被复制到

下面是我的代码:

收到错误:

An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

Additional information: Could not find a part of the path 'C:\Users\Alfred\Source\Workspaces\CIS151_MEY\AlfredM Books XML\AlfredM Books XML\bin\Debug\Data\Books.xml'.
Run Code Online (Sandbox Code Playgroud)

类文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Reflection;

namespace AlfredM_Books_XML
{
    class XmlHelper
    {
        public static XDocument GetBookDocument()
        {
            string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

            FileInfo asm = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

            FileInfo fi = new FileInfo(asm.DirectoryName + @"\Data\Books.xml");

            XDocument doc = XDocument.Load(fi.FullName);
            return doc;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我添加XML文件的地方

在此处输入图片说明

Ark*_*z K 5

选择您的Books.xml文件Solution Explorer,右键单击该文件,然后选择Properties。然后将属性Copy To Output Directory值设置为Copy always