Windows Phone 独立存储 [英] Windows Phone IsolatedStorage

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

问题描述

我有一个应用程序需要在设备上下载和保存文件 - 视频.

I have a application that needs to download and save files on a device - videos.

视频短约 10 分钟,质量很差,这意味着它们的大小很小.

Videos are short ~ 10min and in poor quality, which means that their size is minimal.

所以,问题是当我下载一些文件时 - 一切顺利,但有些文件失败并出现错误:内存不足异常.从逻辑上讲,我认为小于某个大小(例如 50MB)的文件可以很好地下载,但更高 - 例外.

So, the problem is that when i download some files - all goes nice, but some files fail with error: Out of memory exception. Logically i think that files less than some size ( for example 50MB ) download nicely, but higher - exception.

这是我的代码:

private void btnDownload2_Click(object sender, RoutedEventArgs e)
    {
        WebClient webClient = new WebClient();
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
        webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
        webClient.OpenReadAsync(new Uri("http://somelink/video/nameOfFile.mp4"));
    }

void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        try
        {
            if (progressMedia.Value <= progressMedia.Maximum)
            {
                progressMedia.Value = (double)e.ProgressPercentage;
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    protected bool IncreaseIsolatedStorageSpace(long quotaSizeDemand)
    {
        bool CanSizeIncrease = false;
        IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
        //Get the Available space
        long maxAvailableSpace = isolatedStorageFile.AvailableFreeSpace;
        if (quotaSizeDemand > maxAvailableSpace)
        {
            if (!isolatedStorageFile.IncreaseQuotaTo(isolatedStorageFile.Quota + quotaSizeDemand))
            {
                CanSizeIncrease = false;
                return CanSizeIncrease;
            }
            CanSizeIncrease = true;
            return CanSizeIncrease;
        }
        return CanSizeIncrease;
    }

    void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        try
        {
            if (e.Result != null)
            {

                #region Isolated Storage Copy Code
                isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

                bool checkQuotaIncrease = IncreaseIsolatedStorageSpace(e.Result.Length);

                string VideoFile = "PlayFile.wmv";
                isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile);
                long VideoFileLength = (long)e.Result.Length;
                byte[] byteImage = new byte[VideoFileLength];
                e.Result.Read(byteImage, 0, byteImage.Length);
                isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);

                #endregion

                mediaFile.SetSource(isolatedStorageFileStream);
                mediaFile.Play();
                progressMedia.Visibility = Visibility.Collapsed;


            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void mediaFile_MediaEnded(object sender, RoutedEventArgs e)
    {
        MessageBoxResult res = MessageBox.Show("Do you want to Replay the file", "Decide", MessageBoxButton.OKCancel);

        if (res == MessageBoxResult.OK)
        {
            mediaFile.Play();
        }
        else
        {
            isolatedStorageFileStream.Close();
            isolatedStorageFile.Dispose();
            mediaFile.ClearValue(MediaElement.SourceProperty);
        }
    }

异常详情:

System.OutOfMemoryException was unhandled Message: An unhandledSystem.OutOfMemoryException"类型的异常发生在System.Windows.ni.dll

System.OutOfMemoryException was unhandled Message: An unhandled exception of type 'System.OutOfMemoryException' occurred in System.Windows.ni.dll

异常图像:

是否有解决方法?

推荐答案

在响应完全加载时,它完全驻留在内存中.这会导致您的 OutOfMemoryException.解决方案是将响应直接流"到隔离的存储中.

At the time the response is completely loaded, it resides entirely in memory. This is causing your OutOfMemoryException. The solution is to "stream" the response directly into isolated storage.

请注意,以下解决方案目前存在的缺点是您会丢失下载进度信息.

Please note that the solution below currently has the drawback that you are losing download progress information.

public async void btnDownload2_Click()
{
  try
  {
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(new Uri("http://somelink/video/nameOfFile.mp4"), HttpCompletionOption.ResponseHeadersRead);

    response.EnsureSuccessStatusCode();

    using(var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
      bool checkQuotaIncrease = IncreaseIsolatedStorageSpace(e.Result.Length);

      string VideoFile = "PlayFile.wmv";
      using(var isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile))
      {
        using(var stm = await response.Content.ReadAsStreamAsync())
        {
          stm.CopyTo(isolatedStorageFileStream);
        }
      }
    }
  }
  catch(Exception)
  {
    // TODO: add error handling
  }
}

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

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