5

在 WinRT / C# 中,如何将图像下载到本地文件夹以支持缓存在线目录以供离线使用?有没有办法直接下载图像并链接控件以从缓存中获取它们作为后备?

    var downloadedimage = await HttpWebRequest.Create(url).GetResponseAsync();
    StorageFile imgfile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                        "localfile.png", CreationCollisionOption.FailIfExists);

下一步我该怎么做才能将下载的图像存储为 localfile.jpg?

4

5 回答 5

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();
于 2012-06-03T10:35:32.753 回答
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()); 
于 2012-06-01T00:47:41.677 回答
1

如果要下载由 URL 表示的文件,最简单的方法是使用 BackgroundDownloader 类。有关如何使用后台下载器的更多信息,请参阅此页面。

于 2012-06-01T05:46:10.917 回答
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);
于 2012-05-31T15:59:16.900 回答
0

默认情况下,位图图像由 WinRT 缓存,无需开发人员干预。

于 2012-09-18T21:49:49.023 回答