Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download files using UWP in c#

Tags:

c#

uwp

I'm a beginner in programming, and I was wondering what the right way is to download files in UWP I now use this, but it only works like 50% of the time:

public async Task StartDownload()
{
    try
    {
        StorageFile sf = await DownloadsFolder.CreateFileAsync(title.Text, CreationCollisionOption.GenerateUniqueName);
        downloadFolder = (await sf.GetParentAsync()).ToString();
        HttpClient client = new HttpClient();
        byte[] buffer = await client.GetByteArrayAsync(inputURL);
        using (Stream stream = await sf.OpenStreamForWriteAsync())
        {
            stream.Write(buffer, 0, buffer.Length);
        }
        path = sf.Path;
    }
    catch (Exception e)
    {
        MessageDialog dialog = new MessageDialog("Sorry, something went wrong...", "An error...");
        await dialog.ShowAsync();
    }
}

The exception is: "Unhandled exception at 0x750F6D7E (combase.dll in program.exe 0xC000027B; An application-internal exception has occurred (parameters: 0x16E73128, 0x00000001)."

Thanks in advance

like image 777
Daniel Avatar asked Jun 14 '16 07:06

Daniel


1 Answers

There are two ways to do it.
First one is to use HttpClient as you do (this works well with small files)

Second one is to use BackgroundDownloader Class. That's recommended way

 private async void StartDownload_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            Uri source = new Uri(inputURL);

            StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                title.Text, CreationCollisionOption.GenerateUniqueName);

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation download = downloader.CreateDownload(source, destinationFile);

            // Attach progress and completion handlers.
            HandleDownloadAsync(download, true);
        }
        catch (Exception ex)
        {
            LogException("Download Error", ex);
        }
    }
like image 158
Alexej Sommer Avatar answered Sep 19 '22 03:09

Alexej Sommer