windows phone 8:如何从网络下载xml文件并将其保存到本地? [英] windows phone 8: how to download xml file from web and save it to local?

查看:43
本文介绍了windows phone 8:如何从网络下载xml文件并将其保存到本地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Web 下载一个 xml 文件,然后将其保存到本地存储,但我不知道该怎么做.请清楚地帮助我或给我一个例子.谢谢.

I would like to download a xml file from web, then save it to the local storage but I do not know how to do that. Please to help me clearly or give me an example. Thank you.

推荐答案

下载文件是一个庞大的主题,可以通过多种方式完成.我假设您知道 Uri,并希望您所说的本地隔离存储.

Downloading a file is a huge subject and can be done in many ways. I assume that you know the Uri of the file you want to download, and want you mean by local is IsolatedStorage.

我将展示三个例子来说明它是如何实现的(还有其他方法).

I'll show three examples how it can be done (there are also other ways).

1.最简单的示例将通过 WebClient:

public static void DownloadFileVerySimle(Uri fileAdress, string fileName)
{
   WebClient client = new WebClient();
   client.DownloadStringCompleted += (s, ev) =>
   {
       using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
       using (StreamWriter writeToFile = new StreamWriter(ISF.CreateFile(fileName)))
           writeToFile.Write(ev.Result);
   };
   client.DownloadStringAsync(fileAdress);
}

如您所见,我直接将字符串(ev.Result 是一个 string - 这是此方法的缺点)下载到隔离存储.和用法 - 例如在按钮点击之后:

As you can see I'm directly downloading string (ev.Result is a string - that is a disadventage of this method) to IsolatedStorage. And usage - for example after Button click:

private void Download_Click(object sender, RoutedEventArgs e)
{
   DownloadFileVerySimle(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
}

2.在第二种方法(简单但更复杂)中,我将再次使用 WebClient 并且需要异步执行(如果您不熟悉此方法,我建议您阅读 MSDN, Stephen Cleary 博客上的 async-await 以及一些 教程).

2. In the second method (simple but more complicated) I'll use again WebClient and I'll need to do it asynchronously (if you are new to this I would suggest to read MSDN, async-await on Stephen Cleary blog and maybe some tutorials).

首先我需要Task,它会从网络下载Stream:

First I need Task which will download a Stream from web:

public static Task<Stream> DownloadStream(Uri url)
{
   TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>();
   WebClient wbc = new WebClient();
   wbc.OpenReadCompleted += (s, e) =>
   {
      if (e.Error != null) tcs.TrySetException(e.Error);
      else if (e.Cancelled) tcs.TrySetCanceled();
      else tcs.TrySetResult(e.Result);
   };
   wbc.OpenReadAsync(url);
   return tcs.Task;
}

然后我将编写下载文件的方法 - 它也需要异步,因为我将使用 await DownloadStream:

Then I'll write my method downloading a file - it also need to be async as I'll use await DownloadStream:

public enum DownloadStatus { Ok, Error };

public static async Task<DownloadStatus> DownloadFileSimle(Uri fileAdress, string fileName)
{
   try
   {
       using (Stream resopnse = await DownloadStream(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute)))
         using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
         {
            if (ISF.FileExists(fileName)) return DownloadStatus.Error;
            using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
                resopnse.CopyTo(file, 1024);
            return DownloadStatus.Ok;
         }
   }
   catch { return DownloadStatus.Error; }
}

例如在单击按钮后使用我的方法:

And usage of my method for example after Button click:

private async void Downlaod_Click(object sender, RoutedEventArgs e)
{
   DownloadStatus fileDownloaded = await DownloadFileSimle(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
   switch (fileDownloaded)
   {
       case DownloadStatus.Ok:
            MessageBox.Show("File downloaded!");
            break;
       case DownloadStatus.Error:
       default:
            MessageBox.Show("There was an error while downloading.");
            break;
    }
}

此方法可能会出现问题,例如,如果您尝试下载非常大的文件(例如 150 Mb).

This method can have problems for example if you try to download very big file (example 150 Mb).

3.第三种方法 - 使用 WebRequest 再次使用 async-await,但这种方法可以改为通过缓冲区下载文件,因此不会占用太多内存:

3. The third method - uses WebRequest with again async-await, but this method can be changed to download files via buffer, and therefore not to use too much memory:

首先,我需要通过一种将异步返回 Stream 的方法扩展我的 Webrequest:

First I'll need to extend my Webrequest by a method that will asynchronously return a Stream:

public static class Extensions
{
    public static Task<Stream> GetRequestStreamAsync(this WebRequest webRequest)
    {
        TaskCompletionSource<Stream> taskComplete = new TaskCompletionSource<Stream>();
        webRequest.BeginGetRequestStream(arg =>
        {
            try
            {
                Stream requestStream = webRequest.EndGetRequestStream(arg);
                taskComplete.TrySetResult(requestStream);
            }
            catch (Exception ex) { taskComplete.SetException(ex); }
        }, webRequest);
        return taskComplete.Task;
    }
}

然后我可以开始工作并编写我的下载方法:

Then I can get to work and write my Downloading method:

public static async Task<DownloadStatus> DownloadFile(Uri fileAdress, string fileName)
{
   try
   {
      WebRequest request = WebRequest.Create(fileAdress);
      if (request != null)
      {
          using (Stream resopnse = await request.GetRequestStreamAsync())
          {
             using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
             {
                  if (ISF.FileExists(fileName)) return DownloadStatus.Error;
                    using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
                    {
                       const int BUFFER_SIZE = 10 * 1024;
                       byte[] buf = new byte[BUFFER_SIZE];

                       int bytesread = 0;
                       while ((bytesread = await resopnse.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
                                file.Write(buf, 0, bytesread);
                   }
             }
             return DownloadStatus.Ok;
         }
     }
     return DownloadStatus.Error;
  }
  catch { return DownloadStatus.Error; }
}

再次使用:

private async void Downlaod_Click(object sender, RoutedEventArgs e)
{
   DownloadStatus fileDownloaded = await DownloadFile(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
   switch (fileDownloaded)
   {
       case DownloadStatus.Ok:
           MessageBox.Show("File downloaded!");
           break;
       case DownloadStatus.Error:
       default:
           MessageBox.Show("There was an error while downloading.");
           break;
   }
}

当然可以改进这些方法,但我认为这可以让您大致了解它的外观.这些方法的主要缺点可能是它们在前台工作,这意味着当您退出应用程序或点击开始按钮时,下载会停止.如果需要后台下载可以使用 后台文件传输 - 但那是另外一回事了.

Those methods of course can be improved but I think this can give you an overview how it can look like. The main disadvantage of these methods may be that they work in foreground, which means that when you exit your App or hit start button, downloading stops. If you need to download in background you can use Background File Transfers - but that is other story.

如您所见,您可以通过多种方式实现目标.您可以在许多页面、教程和博客上阅读有关这些方法的更多信息,比较选择最合适的.

As you can see you can reach your goal in many ways. You can read more about those methods on many pages, tutorials and blogs, compare an choose the most suitable.

希望这会有所帮助.祝您编程愉快,祝您好运.

Hope this helps. Happy coding and good luck.

这篇关于windows phone 8:如何从网络下载xml文件并将其保存到本地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆