Big Al Ruby Newbie
Big Al Ruby Newbie

Reputation: 834

DirectoryNotFoundException C# error loading an XML File into Console App

I am new to C# and trying to parse an XML Document but i keep getting an error that directory was not found

Apparently my xml file and data folder is not being coppied to \bin\Debug when program starts

Below is my code:

Error Received:

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'.

Class File:

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;
        }
    }
}

This is where i added my XML File

enter image description here

Upvotes: 1

Views: 945

Answers (2)

Joe DeCock
Joe DeCock

Reputation: 80

You need to explicitly tell msbuild to copy the file during the build. To do so, right click on the file in the solution explorer, choose properties, and then change Copy to output directory.

Upvotes: 0

Arkadiusz K
Arkadiusz K

Reputation: 1827

Select your Books.xml file in Solution Explorer, right click on that file and select Properties. Then set property Copy To Output Directory value to Copy always.

Upvotes: 5

Related Questions