Charley Westman
Charley Westman

Reputation: 3

DirectoryNotFoundException was unhandled by user code? (Visual Studio 2013, C#)

When I try to run this program, which writes details about a book to an xml file when a button is clicked, I get a DirectoryNotFoundException. How can I rewrite the address for my books.xml file under the App_Data folder?

Here are the details about the error.

An exception of type 'System.IO.DirectoryNotFoundException' occurred in System.Xml.dll but was not handled in user code

Additional information: Could not find a part of the path 'C:\App_Data\books.xml'.

Here is the Default.aspx code for reference:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace LibraryShelf
{
    public partial class Default : System.Web.UI.Page
    {
        //protected void Page_Load(object sender, EventArgs e)
        //{

        //}

        static void addNode(string fileName, XmlDocument xmlDoc)
        {
            XmlElement bookElement = xmlDoc.CreateElement("book");
            bookElement.SetAttribute("name", "DotNet Made Easy");

            XmlElement authorElement = xmlDoc.CreateElement("author");
            authorElement.InnerText = "microsoft";
            bookElement.AppendChild(authorElement);

            XmlElement priceElement = xmlDoc.CreateElement("price");
            priceElement.InnerText = "50";
            bookElement.AppendChild(priceElement);

            xmlDoc.DocumentElement.AppendChild(bookElement);
            xmlDoc.Save(fileName);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string fileName = System.IO.Path.Combine(Request.ApplicationPath, "App_Data/books.xml");

            XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
            XmlDocument _xmlDocument = new XmlDocument();
            _xmlDocument.Load(_xmlTextReader);

            //Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
            //being used by another process.
            _xmlTextReader.Close();

            addNode(fileName, _xmlDocument);
        }
    }
}

Upvotes: 0

Views: 3699

Answers (2)

Guffa
Guffa

Reputation: 700720

The application folder is not the physical path to the web site, it's the path from the domain root to the application root. This is usually an empty string, unless you are using a virtual directory or an application subfolder on the server.

Use the MapPath method to get the physical path of a virtual address:

string fileName = Server.MapPath("~/App_Data/books.xml");

Upvotes: 3

Rohit
Rohit

Reputation: 1550

try this -

string path = System.IO.Path.GetFullPath(Server.MapPath("~/App_Data/books.xml"));

Server.MapPath will get you the location of the file.

Upvotes: 0

Related Questions