在Windows Phone中异步下载后,将Stream转换为字节数组

时间:2013-09-05 17:37:11

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

我从一个网站异步下载图像。我想将图像列表保存到IsolatedStorage中。并且流不可序列化,因此我必须将其转换为字节数组。但它并没有在 ReadFully ()方法的循环中读取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

1 个答案:

答案 0 :(得分:3)

因为您在传递imageStream之前在创建bitmapImage时使用了流ReadFully

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