Downloading XML from URL
本文关键字:URL from XML Downloading | 更新日期: 2023-09-27 18:02:52
我正试图找到一种方法在windows手机上下载XML文件,该文件稍后将被解析为在集合中使用。现在我尝试了与WPF应用程序相同的方法,即:
public void downloadXml()
{
WebClient webClient = new WebClient();
Uri StudentUri = new Uri("url");
webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(fileDownloaded);
webClient.DownloadFileAsync(StudentUri, @"C:/path");
}
当移动到Windows Phone时,web客户端失去DownloadFileAsync
和DownloadFileCompleted
功能。那么,是否有另一种方法来做到这一点,我将不得不使用IsolatedStorageFile
,如果是这样,如何解析它?
我试图在我的机器上重现您的问题,但根本没有找到WebClient
类。所以我用WebRequest
代替。
第一个是WebRequest
的helper类:
public static class WebRequestExtensions
{
public static async Task<string> GetContentAsync(this WebRequest request)
{
WebResponse response = await request.GetResponseAsync();
using (var s = response.GetResponseStream())
{
using (var sr = new StreamReader(s))
{
return sr.ReadToEnd();
}
}
}
}
第二个家伙是IsolatedStorageFile
的助手类:
public static class IsolatedStorageFileExtensions
{
public static void WriteAllText(this IsolatedStorageFile storage, string fileName, string content)
{
using (var stream = storage.CreateFile(fileName))
{
using (var streamWriter = new StreamWriter(stream))
{
streamWriter.Write(content);
}
}
}
public static string ReadAllText(this IsolatedStorageFile storage, string fileName)
{
using (var stream = storage.OpenFile(fileName, FileMode.Open))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
}
最后一个解决方案,用法示例:
private void Foo()
{
Uri StudentUri = new Uri("uri");
WebRequest request = WebRequest.Create(StudentUri);
Task<string> getContentTask = request.GetContentAsync();
getContentTask.ContinueWith(t =>
{
string content = t.Result;
// do whatever you want with downloaded contents
// you may save to isolated storage
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
storage.WriteAllText("Student.xml", content);
// you may read it!
string readContent = storage.ReadAllText("Student.xml");
var parsedEntity = YourParsingMethod(readContent);
});
// I'm doing my job
// in parallel
}