2009-04-11 178 views
1

我觉得有点愚蠢,甚至问这个问题, 但我坐在一个小时试图找出如何解决问题。 我目前正在做一个项目,使用ASP.NET和XML,对于我的项目,我从Visual Studio创建了新的网站,并试图将我的XML文件保留在App_Data中。无法找到xml路径错误

然而,当我尝试使用代码:

var topic = from t in XElement.Load("App_Data/topics.xml").Elements("topics") 
        select new 
        { 
         topic_id = t.Attribute("id"), 
         topic_subject = t.Element("topicname"), 
         topic_short_body = t.Element("topicshortbody") 
        }; 

我得到一个错误:

Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path 'c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\App_Data\topics.xml'. 

Source Error: 

Line 23:  { 
Line 24: 
Line 25:   var topic = from t in XElement.Load("App_Data/topics.xml").Elements("topics") 
Line 26:      select new 
Line 27:      { 


Source File: d:\college\xml\xmlproject\Default.aspx.cs Line: 25 

我绝对相信我的文件中的App_Data。 所以我的问题是否有其他方式来指定路径,或者如何在我的情况下指定路径的正确方法?

预先感谢您。

回答

3

使用Request.ApplicationPath

XElement.Load(Request.ApplicationPath + "/App_Data/topics.xml"); 

这将确保您试图加载在正确的位置的文件,默认情况下该过程在“C运行:\ Program Files文件\微软的Visual Studio 9.0 \ Common7 \ IDE \“(调试Web服务器),在生产服务器上,该路径很可能位于C:\ windows \ system32 \或IIS进程所在的位置。

在ASP.NET中处理文件时,务必使路径为绝对路径。

您也可以使用System.IO.Path.Combine(Request.ApplicationPath,“App_Data/topics.xml”)来确保您的字符串concat是'正确的'。

3

因为它可能对其他人有用。 我找到的另一种解决方案

String xmlpath = Server.MapPath("App_Data/topics.xml");