我有两种功能相同的方法:
private static async Task<IRandomAccessStream> _DownloadImage(string url)
{
HttpClient http = new HttpClient();
var httpStream = await http.GetStreamAsync(url);
var memStream = new MemoryStream();
await httpStream.CopyToAsync(memStream);
memStream.Seek(0, SeekOrigin.Begin);
return memStream.AsRandomAccessStream();
}
和
private static async Task<IRandomAccessStream> _DownloadImage2(string url)
{
HttpClient http = new HttpClient();
var httpStream = await http.GetStreamAsync(url);
var stream = new InMemoryRandomAccessStream();
await httpStream.CopyToAsync(stream.AsStreamForWrite());
stream.Seek(0);
return stream;
}
问题是,对于某些网址,第二个版本的长度为stream
。这是一个错误还是我错过了什么?
第一个版本为普通流提供图片而第二个版本为空的网址:http://icdn.lenta.ru/images/2014/09/17/10/20140917102331786/pic_ffa73ea27023b3e69b6cef4d068c0499.jpg
UPD:
我发现大小低于16384的文件存在风险。我在AsStreamForWrite文档中找到了这个16384值。 @Kiewic,也提出了一个解决方法。我仍然想知道为什么它不能正常工作。
UPD2: 在Connect。中创建了bug report。
答案 0 :(得分:1)
当您将Stream
保留在变量中时,它会起作用,请尝试:
// using System.Net.Http;
private static async Task<IRandomAccessStream> _DownloadImage2(string url)
{
HttpClient http = new HttpClient();
var httpStream = await http.GetStreamAsync(url);
var stream = new InMemoryRandomAccessStream();
Stream streamForWrite = stream.AsStreamForWrite();
await httpStream.CopyToAsync(streamForWrite);
stream.Seek(0);
Debug.WriteLine("Length: " + streamForWrite.Length);
Debug.WriteLine("Size: " + stream.Size);
return stream;
}