Reputation: 26645
I am asynchronously downloading images from one web site.And I want to save list of images into IsolatedStorage. And stream is not serializable, so I have to convert it to byte array. But it is not reading Stream in while loop in ReadFully() method.
Here is how I am trying to download images:
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);
And here is the method for converting stream to byte array:
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();
}
}
Update:
It is not getting inside the while loop. So the byte array is always empty.
Upvotes: 2
Views: 2370
Reputation: 35353
Because you are consuming the stream imageStream
in creating bitmapImage
before passing to ReadFully
.
First get the byte[]
, then use it to form the image and to pass to new DownloadedImages()
Upvotes: 3