WinRT StorageFile write downloaded file
Asked Answered
V

3

9

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?

Varnish answered 6/7, 2012 at 13:31 Comment(0)
V
12

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;
    }
Varnish answered 19/7, 2012 at 14:58 Comment(1)
Great answer. Simple and it works perfectly. No more problems while reading "not complete" files. Thanks alot man.Anabasis
T
7

You will need to read the response stream into a buffer then write the data to a StorageFile. THe following code shows an example:

        var fStream = responsePic.GetResponseStream();
        var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("testfile.txt");
        using (var ostream = await file.OpenStreamForWriteAsync())
        {
            int count = 0;
            do
            {
                var buffer = new byte[1024];
                count = fStream.Read(buffer, 0, 1024);
                await ostream.WriteAsync(buffer, 0, count);
            }
            while (fStream.CanRead && count > 0);
        }
Translative answered 7/7, 2012 at 5:54 Comment(0)
C
0

That can be done using the C++ REST SDK in Windows Store Apps. It's explained by HTTP Client Tutorial.

Charlotte answered 27/8, 2015 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.