I'm trying to retrieve an XML document from a server and store it locally as a string. In desktop .Net I didn't need to, I just did:
string xmlFilePath = "https://myip/";
XDocument xDoc = XDocument.Load(xmlFilePath);
However on WP7 this returns:
Cannot open 'serveraddress'. The Uri parameter must be a relative path pointing to content inside the Silverlight application's XAP package. If you need to load content from an arbitrary Uri, please see the documentation on Loading XML content using WebClient/HttpWebRequest.
So I set about using the WebClient/HttpWebRequest example from here, but now it returns:
The remote server returned an error: NotFound.
Is it because the XML is a https path? Or because my path doesn't end in .XML? How do I find out? Thanks for any help.
Here's the code:
public partial class MainPage : PhoneApplicationPage
{
WebClient client = new WebClient();
string baseUri = "https://myip:myport/service";
public MainPage()
{
InitializeComponent();
client.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(
client_DownloadStringCompleted);
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
client.DownloadStringAsync
(new Uri(baseUri));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
resultBlock.Text = "Using WebClient: " + e.Result;
else
resultBlock.Text = e.Error.Message;
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(new Uri(baseUri));
request.BeginGetResponse(new AsyncCallback(ReadCallback),
request);
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 =
new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
resultBlock.Text = "Using HttpWebRequest: " + resultString;
}
}
}