在WinRT / C#中,如何将图像下载到本地文件夹以支持在线目录的缓存以供离线使用?有没有办法直接下载图像并链接控件以从缓存中获取它们作为后备?
var downloadedimage = await HttpWebRequest.Create(url).GetResponseAsync();
StorageFile imgfile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"localfile.png", CreationCollisionOption.FailIfExists);
我将下载的图像存储为localfile.jpg?
答案 0 :(得分:10)
看起来以下来自Windows 8的HttpClient示例中的代码解决了问题
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, resourceAddress);
HttpResponseMessage response = await rootPage.httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead);
httpClient是一个HttpClient,其BaseAddress需要设置为资源的服务器文件夹。然后,我们可以将其转换为图像源(如果这就是我们正在下载的内容)
InMemoryRandomAccessStream randomAccessStream =
new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
BitmapImage image = new BitmapImage();
imagecontrol.SetSource(randomAccessStream);
或将其写入文件
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
filename, CreationCollisionOption.ReplaceExisting);
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();
答案 1 :(得分:3)
试试这个:
var response = await HttpWebRequest.Create(url).GetResponseAsync();
List<Byte> allBytes = new List<byte>();
using (Stream imageStream = response.GetResponseStream())
{
byte[] buffer = new byte[4000];
int bytesRead = 0;
while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0)
{
allBytes.AddRange(buffer.Take(bytesRead));
}
}
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"localfile.png", CreationCollisionOption.FailIfExists);
await FileIO.WriteBytesAsync(file, allBytes.ToArray());
答案 2 :(得分:1)
如果要下载由URL表示的文件,最简单的方法是使用BackgroundDownloader类。有关如何使用后台下载程序的详细信息,请参阅this页面。
答案 3 :(得分:0)
GetResponseAsync将为您提供WebResponse文件,而不是图像:
Stream imageStream = downloadedimage.GetResponseStream();
然后你可以写到图像文件:
byte[] imageData = new byte[imageStream.Length];
using(StreamReader reader = new Streamreader(imageStream))
{
reader.ReadBytes(imageData, 0, imageData.Length);
}
await FileIO.WriteBytesAsync(imgfile, imageData);
答案 4 :(得分:0)
默认情况下,位图图像由WinRT缓存,开发人员无需干预。