Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinRT StorageFile write downloaded file

I'm struggling with a easy problem. I want to download an image from web using this code:

WebRequest requestPic = WebRequest.Create(@"http://something.com/" + id + ".jpg");
WebResponse responsePic = await requestPic.GetResponseAsync();

Now I wanted to write the WebResponse's stream in a StorageFile (eg. create a file id.jpg in the app's storage), but I haven't found any way to achieve that. I searched the web for it, but no success - all ways incompatible Stream types and so on.

Could you please help?

like image 223
Martin Zikmund Avatar asked Jul 06 '12 13:07

Martin Zikmund


1 Answers

I have found the following solution, which works and is not too complicated.

    public async static Task<StorageFile> SaveAsync(
        Uri fileUri,
        StorageFolder folder,
        string fileName)
    {
        var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
        var downloader = new BackgroundDownloader();
        var download = downloader.CreateDownload(
            fileUri,
            file);

        var res = await download.StartAsync();            

        return file;
    }
like image 59
Martin Zikmund Avatar answered Oct 18 '22 23:10

Martin Zikmund