Search code examples
asynchronousxamarinfilestreamxamarin.formsdotnet-httpclient

Download file with progress bar in Xamarin Forms


I am trying to make a download page in Xamarin Forms (PCL, so WebClient is not usable) with a Download progress bar. I have used the following information from Xamarin, but without success:

http://developer.xamarin.com/recipes/ios/network/web_requests/download_a_file/ http://developer.xamarin.com/recipes/cross-platform/networking/download_progress/

This is my current code (with a working progress bar):

using System;
using System.Collections.Generic;

using Xamarin.Forms;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;

namespace DownloadExample
{
    public partial class DownloadPage : ContentPage
    {
        public DownloadPage ()
        {
            InitializeComponent ();

            DownloadFile("https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg");
        }

        private async Task<long> DownloadFile(string url)
        {
            long receivedBytes = 0;
            long totalBytes = 0;
            HttpClient client = new HttpClient ();

            using (var stream = await client.GetStreamAsync(url)) {
                byte[] buffer = new byte[4096];
                totalBytes = stream.Length;

                for (;;) {
                    int bytesRead = await stream.ReadAsync (buffer, 0, buffer.Length);
                    if (bytesRead == 0) {
                        await Task.Yield ();
                        break;
                    }

                    receivedBytes += bytesRead;

                    int received = unchecked((int)receivedBytes);
                    int total = unchecked((int)totalBytes);

                    double percentage = ((float) received) / total;

                    progressBar1.Progress = percentage;
                }
            }

            return receivedBytes;
        }
    }
}

Now, I need to save the file to my local storage. But, in this example, I'm not getting the file content, so I can't write it to my local storage. What do I need to change in the code to make this possible?

FYI: In this example, I'm downloading an image, but it will be a .pdf / .doc / .docx in feature.

Thanks in advance.

BR, FG


Solution

  • You actually copy the file content to your buffer inside the for loop. Concat the buffer content each run of that loop into a new byte[] fileContentBuffer and you have access to the contents which you can save in the local storage.