简体   繁体   中英

Windows 8.1 store xaml download and save file in synchronize

I'm trying to download a file and pause it then resume it and pass the latest Range header to it and seek to part i have downloaded in the file then continue writing on it.

The problem is that when i use a cancellation token to pause my download then i lose the part i downloaded in the response object and it becomes null ....so how can i download and write file at the same time in synchronized manner ?

Here is my code:

Windows Store app 8.1 Xaml pausing/resuming download using http classes

and i'm limited in using it because it provides authentication and header in the download.

Please do not suggest using the background downloader api except that you have tested the pause functionality in it your self, because i did test it my self and it rarely worked properly .

The example at the link you provided copies the source stream to the dest stream in a single call. If you want to be able to resume a cancelled download, then you should get the source stream and then read/write small chunks in a loop. Then if the download was cancelled for any reason, before you restart the download you can check the size of the partial file that you have already downloaded and set the appropriate range header.

Edit (Adding sample code):

using (Stream destStream = await destFile.OpenStreamForWriteAsync())
{
    using (HttpClient httpClient = new HttpClient())
    {
        var s = await httpClient.GetInputStreamAsync(new Uri(srcUrl));

        using (Stream srcStream = s.AsStreamForRead())
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = srcStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                destStream.Write(buffer, 0, read);
            }
        }                  
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM