Draas
Draas

Reputation: 21

How to download files in Xamarin.Forms?

Good day everyone! I am stuck on a problem. We decided that for some reasons we need to make our own launcher for a game which will check its version and download .apk of the game to install. We dont have a xamarin developer in our team, so I was asked to try do it myself. Stuck on downloading for the 2nd day. I installed NuGet plugin DownloadManager, tried to use it and did not succeed. Some indian guy video's didn't help me either. I can make a game, but totally suck in mobile development. What should I do?

I tried:

  1. Making IDownloader(url, folder) with EventHandler, that did not help
  2. Using plugin with these code. Linked it to a button. This did not help me too. Your help will save my life
void DownloadFile() 
{
    var downloadManager = CrossDownloadManager.Current;
    var file = downloadManager.CreateDownloadFile("someURIGodSaveMe");
    downloadManager.Start(file);
}

Upvotes: 0

Views: 4524

Answers (1)

Michal Diviš
Michal Diviš

Reputation: 2216

You don't need anything special to download files in Xamarin.Forms, the good old HttpClient does the job.

This code downloads a file from a URL to the apps internal storage. More about Environment.SpecialFolder.Personal in Xamarin.Forms here.

private async Task DownloadApkAsync()
{
    var downloadedFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "myApp_v1.2.3.apk");

    var success = await DownloadFileAsync("https://www.myapp.com/apks/v1.2.3.apk", downloadedFilePath);

    if (success)
    {
        Console.WriteLine($"File downloaded to: {downloadedFilePath}");
    }
    else
    {
        Console.WriteLine("Download failed");
    }
}

private async Task<bool> DownloadFileAsync(string fileUrl, string downloadedFilePath)
{
    try
    {
        using var client = new HttpClient();

        var downloadStream = await client.GetStreamAsync(fileUrl);

        using var fileStream = File.Create(downloadedFilePath);

        await downloadStream.CopyToAsync(fileStream);

        return true;
    }
    catch (Exception ex)
    {
        //TODO handle exception
        return false;
    }
}

I also found this very nice tutorial for downloading large files in Xamarin.Forms if you want to get fancy (haven't tried it though). It supports download progress bar and cancellation.

Upvotes: 4

Related Questions