Windows phone 8 windows phone 8:如何从web下载xml文件并将其保存到本地?

Windows phone 8 windows phone 8:如何从web下载xml文件并将其保存到本地?,windows-phone-8,Windows Phone 8,我想从web下载一个xml文件,然后将其保存到本地存储,但我不知道如何做到这一点。请帮我弄清楚或者给我举个例子。谢谢。下载文件是一个庞大的主题,可以通过多种方式完成。我假设您知道要下载的文件的名称,并且希望您所说的本地是 我将展示三个示例如何实现(还有其他方法) 1。最简单的示例将通过以下方式加载字符串: 如您所见,我正在直接下载string(ev.Result是一个string-这是该方法的一个缺点)以隔离存储。 和用法-例如,单击按钮后: private void Download_Clic

我想从web下载一个xml文件,然后将其保存到本地存储,但我不知道如何做到这一点。请帮我弄清楚或者给我举个例子。谢谢。

下载文件是一个庞大的主题,可以通过多种方式完成。我假设您知道要下载的文件的名称,并且希望您所说的本地是

我将展示三个示例如何实现(还有其他方法)

1。最简单的示例将通过以下方式加载字符串:

如您所见,我正在直接下载string(
ev.Result
是一个
string
-这是该方法的一个缺点)以隔离存储。 和用法-例如,单击按钮后:

private void Download_Click(object sender, RoutedEventArgs e)
{
   DownloadFileVerySimle(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
}
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;
    }
}
2。在第二种方法中(简单但更复杂),我将再次使用
WebClient
,并且我需要异步执行(如果您不熟悉这一方法,我建议您阅读,或者阅读一些)

首先我需要
任务
,它将从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;
}
这种方法可能会有问题,例如,如果您试图下载非常大的文件(例如150MB)

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

首先,我需要通过异步返回
流的方法扩展我的
Webrequest

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;
    }
}
这些方法当然可以改进,但我认为这可以让您大致了解它的外观。这些方法的主要缺点可能是它们在前台工作,这意味着当你退出应用程序或点击开始按钮时,下载停止。若你们需要在后台下载,你们可以使用——但这是另一个故事

正如你所看到的,你可以通过多种方式实现你的目标。你可以在许多网页、教程和博客上阅读更多关于这些方法的信息,比较并选择最合适的方法


希望这有帮助。祝您编码愉快,好运。

谢谢Romasz。保存此文件后,您能告诉我IsolatedStorage文件夹在我的计算机中的位置吗。@Carson IsolatedStorage文件夹在您的手机中,这是严格连接到您的应用程序的“位置”,没有其他应用程序可以访问它。不过,您当然可以通过或通过例如来探索您的开发人员设备(或模拟器)。@Carson欢迎您。另请参阅我提到的(在下一次编辑之后)关于后台下载的内容——它有时可能很有用。高兴的coding@Carson然后您发现了下载字符串的下一个缺点;)-事实上,字符串可以有不同的编码。为了解决您的问题,您可能只需要更改streamwriter的编码,下面的一行应该修复您的文件大小:使用(streamwriter writeToFile=new streamwriter(ISF.CreateFile(fileName),encoding.Unicode)),我要感谢您数千次。我的每一个问题都解决了。
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;
    }
}
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;
    }
}
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;
   }
}