我正在从一个网站异步下载图像。我想将图像列表保存到独立存储中。而且流不可序列化,所以我必须将其转换为字节数组。但它不是在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循环。所以字节数组总是空的。