Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

c# - Download an image to local storage in Metro style apps

In WinRT / C#, How do I download an image to a local folder to support caching of an online catalogue for offline use? is there a way to directly download the images and link the control to get them from the cache as a fallback?

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

What do I do next to store downloadedimage as localfile.jpg?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like the code below from the HttpClient sample for Windows 8 solves the issue

    HttpRequestMessage request = new HttpRequestMessage(
        HttpMethod.Get, resourceAddress);
    HttpResponseMessage response = await rootPage.httpClient.SendAsync(request,
        HttpCompletionOption.ResponseHeadersRead);

httpClient is a HttpClient, and its BaseAddress needs to be set a the server folder of your resource. we can then do this to convert that to an image source (if that's what we're downloading)

    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);

or this to write it to file

    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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...