Loading local xml file in Windows Phone 7 (WP7)

user537303 picture user537303 · Dec 10, 2010 · Viewed 11.7k times · Source

I am trying to load up an XML file that lives in my Windows Phone 7 solution. I'd like to know the proper way to include the file in the project and then reference it with code. My current code is giving me an error of

NotSupportedException "An exception occurred during a WebClient request."

here is the stub of my WebClient code

WebClient workbenchAdConfigRequest = new WebClient();
workbenchAdConfigRequest.OpenReadCompleted += new OpenReadCompletedEventHandler(workbenchAdConfigRequest_OpenReadCompleted);
workbenchAdConfigRequest.OpenReadAsync(new Uri("/SampleData/SampleData.xml", UriKind.Relative));

and the event handler is

private void workbenchAdConfigRequest_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        try
        {
            XElement xml = XElement.Load(e.Result);         
        }
        catch
        {
            //return
        }
    }

on the file /SampleData/SampleData.xml I have set the properties to be

Build Action: Embedded Reference Copy to Output Directory: Do Not Copy Custom Tool: MSBuild:Compile

Can you load a local file from the "file path" of the application?

Answer

Gerardo Melendrez picture Gerardo Melendrez · Dec 21, 2010

You can also set the "Build Action" to "Content" in the properties of your XML file, and then in the code behind:

using System.Xml.Linq;

......

XElement appDataXml;

StreamResourceInfo xml = Application.GetResourceStream(new Uri("yourxmlfilename.xml", UriKind.Relative)); 
appDataXml = XElement.Load(xml.Stream);