views:

943

answers:

2

I feel kinda stupid to even ask that question, But i was sitting like an hour trying to figure out how to solve the problem. I am currently making a project that uses ASP.NET and XML, for my project i created new web site from Visual Studio, and trying to keep my XML files in App_Data.

However when i trying to use code:

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

I am getting an error :

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

I am absolutely sure that my file in App_Data. So my question is there other way to specify path, or how it would be in my case proper way to specify the path ?

Thank you in advance.

+2  A: 

Use Request.ApplicationPath

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

This will ensure that your attempting to load the file at the correct location, by default the process is running in "c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\" (the debug web server), on a production server the path would most likely be in C:\windows\system32\ or whereever the IIS process is located.

Always make your paths absolute when working with files in ASP.NET.

You can also use System.IO.Path.Combine(Request.ApplicationPath, "App_Data/topics.xml") to ensure your string concat is 'correct'.

David Higgins
+1  A: 

Since it might be useful to somebody else. Another solution that I found

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