当我尝试运行该程序时,如果单击按钮时会将书籍的详细信息写入xml文件,则会出现DirectoryNotFoundException。我该如何重写App_Data文件夹下我的books.xml文件的地址?DirectoryNotFoundException由用户代码未处理? (Visual Studio 2013,C#)
以下是有关错误的详细信息。
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'.
下面是Default.aspx的代码,以供参考:
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);
}
}
}
你有'App_Data'文件夹吗? –
那么,你确定目录和文件存在?! –
WRT你的代码:你应该在[using语句](http://msdn.microsoft.com/en-us/library/yh598w02.aspx)中声明并实例化XmlTextReader,按照[这里的例子](http:// msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx)。 – BCdotWEB