从URL下载XML

时间:2014-05-11 22:33:40

标签: c# xml windows-phone-8 webclient

我正在尝试找到一种在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会丢失DownloadFileAsyncDownloadFileCompleted功能。那么还有另一种方法吗?我必须使用IsolatedStorageFile,如果是这样,如何解析它?

1 个答案:

答案 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
}

希望这有帮助。