c# - Windows Phone中异步下载后将Stream转换为字节数组

标签 c# .net silverlight windows-phone-7

我正在从一个网站异步下载图像。并且我想将图像列表保存到IsolatedStorage 中。而且流不可序列化,所以我必须将其转换为字节数组。但它不是在 ReadFully() 方法中的 while 循环中读取 Stream。

这是我尝试下载图像的方法:

    HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
    request.Headers["Referer"] = "http://www.website.com";
    request.BeginGetResponse((result) =>
    {
        Stream imageStream = request.EndGetResponse(result).GetResponseStream();
        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            // Set stream as the source of image
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
            bitmapImage.SetSource(imageStream);
            image.Source = bitmapImage;

            // Convert stream to byte array and save in the custom list with the uri of the image 
            ls.Add(new DownloadedImages() { Image = ReadFully(imageStream), URI = uri });
            ds.SaveMyData(ls, "BSCImages");
        });
    }, null);

这是将流转换为字节数组的方法:

 public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[input.Length];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

更新:

它没有进入 while 循环。所以字节数组总是空的。 enter image description here

最佳答案

因为在传递给 ReadFully 之前,您在创建 bitmapImage 时消耗了流 imageStream

首先获取byte[],然后使用它形成图像并传递给new DownloadedImages()

关于c# - Windows Phone中异步下载后将Stream转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18642596/

相关文章:

c# - 从本地时间中删除秒数但保留格式

silverlight - 如何在 Silverlight BackgroundWorker 中运行批处理 WCF 服务调用

C# - IoC - WebAPI 2 上的 Autofac 依赖注入(inject)

c# - 删除用户的声明

c# - 命令行参数中的反斜杠和引号

c# - DataGridView 列自动调整宽度和可调整大小

c# - 如何通过 .NET API 打开 AutoCAD 2015

c# - LINQ 查询匹配两个项目列表

c# - C# 中的 XML 解析(在 C# 中修复 XML 文档)

c# - VirtualizingStackPanel 和 TextWrapping 错误? Windows Mobile