我正在尝试找到一种在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时,webclient会丢失DownloadFileAsync
和DownloadFileCompleted
功能。那么还有另一种方法吗?我必须使用IsolatedStorageFile
,如果是这样,如何解析它?
答案 0 :(得分:1)
我试图在我的机器上重现您的问题,但根本没有找到WebClient
课程。所以我改用WebRequest
。
所以,第一个人是WebRequest
的助手类:
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
}
希望这有帮助。