2015-01-16 69 views
0

当我尝试运行该程序时,如果单击按钮时会将书籍的详细信息写入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); 
     } 
    } 
} 
+0

你有'App_Data'文件夹吗? –

+0

那么,你确定目录和文件存在?! –

+0

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

回答

2

的应用程序文件夹是不是该网站的物理路径,这是从域根到应用程序根目录的路径。这通常是一个空字符串,除非您在服务器上使用虚拟目录或应用程序子文件夹。

使用MapPath方法来获取虚拟地址的物理路径:

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

太棒了。这效果很好!谢谢! –

0

试试这个 -

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

Server.MapPath将让你的文件的位置。

相关问题