直接在 WP8 中保存到独立存储 [英] Save to isolated storage directly in WP8

查看:21
本文介绍了直接在 WP8 中保存到独立存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 zip 文件直接保存到与服务器隔离的存储中,但我面临的问题是当我尝试使用以下代码进行保存时,由于我的文件大小有时大于 150 MB,因此出现内存不足异常.所以我在这里发布了一个问题,建议是

I want to save a zip file directly to isolated storage from server , But the problem i am facing was when i try to save using the below code , i get out of memory exception since my file size is > 150 MB some times. So i posted a question here and the suggestion was

您可以将这样的文件直接下载到IsolatedStorage,但如果您想将其放入内存中,可能会出现问题.

you can download such a file directly to IsolatedStorage, but if you want to put that into Memory - there can be a problem.

那么如何将文件从服务器直接保存到独立存储而不保存到内存.我使用的代码发布在这里

So how can i save a file from server directly to isolated storage without saving to memory . The code i used is posted here

client = new WebClient();
    client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
    client.OpenReadAsync(new Uri(fileurl), objRef);

    private async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {

            var file = IsolatedStorageFile.GetUserStoreForApplication();
            if (!file.DirectoryExists("Folderpath/Files"))
            {
                file.CreateDirectory("Folderpath/Files");
            }
            string hpubFile = "/Folderpath/Files/fileName" ;
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(hpubFile, System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, file))
            {
                byte[] buffer = new byte[1024];
                while (e.Result.Read(buffer, 0, buffer.Length) > 0)
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }
        }
    }

推荐答案

那么也许可以试试这样的方法——用 HttpWebRequest 来做:

Then maybe try such an approach - do it with HttpWebRequest:

    1.首先使用可等待的 GetResponseAsync 扩展您的 HttpWebRequest - WP 缺少此方法,但使用 TaskCompletitionSource 您可以编写自己的实现.在您的命名空间中,创建一个静态类:

      1. First extend your HttpWebRequest with awaitable GetResponseAsync - WP lacks this method, but with TaskCompletitionSource you can write your own implementation. Somwhere in your Namespace, make a static class:

      public static class Extensions
      {
          public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest webRequest)
          {
              TaskCompletionSource<HttpWebResponse> taskComplete = new TaskCompletionSource<HttpWebResponse>();
              webRequest.BeginGetResponse(
                  asyncResponse =>
                  {
                      try
                      {
                          HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
                          HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
                          taskComplete.TrySetResult(someResponse);
                      }
                      catch (WebException webExc)
                      {
                          HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
                          taskComplete.TrySetResult(failedResponse);
                      }
                      catch (Exception exc) { taskComplete.SetException(exc); }
                  }, webRequest);
              return taskComplete.Task;
          }
      }
      

        2.然后修改您的代码以使用它:

          2. Then modify your code to use it:

          CancellationTokenSource cts = new CancellationTokenSource();
          enum Problem { Ok, Cancelled, Other };
          
          public async Task<Problem> DownloadFileFromWeb(Uri uriToDownload, string fileName, CancellationToken cToken)
          {
              try
              {
                  HttpWebRequest wbr = WebRequest.CreateHttp(uriToDownload);
                  wbr.Method = "GET";
                  wbr.AllowReadStreamBuffering = false;
                  WebClient wbc = new WebClient();
          
                  using (HttpWebResponse response = await wbr.GetResponseAsync())
                  {
                      using (Stream mystr = response.GetResponseStream())
                      {
                          using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
                            {
                                if (ISF.FileExists(fileName)) return Problem.Other;
                                using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
                                {
                                    const int BUFFER_SIZE = 100 * 1024;
                                    byte[] buf = new byte[BUFFER_SIZE];
          
                                    int bytesread = 0;
                                    while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
                                    {
                                        cToken.ThrowIfCancellationRequested();
                                        file.Write(buf, 0, bytesread);
                                    }
                                }
                            }
                            return Problem.Ok;
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (exc is OperationCanceledException)
                        return Problem.Cancelled;
                    else return Problem.Other; 
                }
            }
          

            3.并下载:

              private async void Downlaod_Click(object sender, RoutedEventArgs e)
              {
                  cts = new CancellationTokenSource();
                  Problem fileDownloaded = await DownloadFileFromWeb(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt", cts.Token);
                  switch(fileDownloaded)
                  {
                      case Problem.Ok:
                          MessageBox.Show("Problem with download");
                          break;
                      case Problem.Cancelled:
                          MessageBox.Show("Download cancelled");
                          break;
                      case Problem.Other:
                      default:
                          MessageBox.Show("Other problem with download");
                          break;
                  }
              }
            

            因为我有我的 WebResponse,所以我从中获取一个流,然后异步读取它.
            请注意,我还没有测试过上面的代码,但希望它可以给您一些想法.

            As I've my WebResponse, I get a stream from it and then read it async.
            Please be aware that I've not tested the code above, but hopefuly it may give you some ideas how this can work.

            这篇关于直接在 WP8 中保存到独立存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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