【问题标题】:Downloading XML from URL从 URL 下载 XML
【发布时间】:2014-05-11 22:33:40
【问题描述】:

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

【问题讨论】:

  • 当您说要再次解析文件时,为什么不将其下载为字符串?我的意思是 webClient.DownloadStringAsync?

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


【解决方案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
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2013-07-26
    • 2016-11-30
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多