如何在C#中使用UWP下载文件 [英] How to download files using UWP in c#

查看:49
本文介绍了如何在C#中使用UWP下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程的初学者,我想知道现在使用UWP下载文件的正确方法是什么,但它只能在50%的时间内工作:

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();
    }
}

例外是:"0x750F6D7E处未处理的异常(program.exe 0xC000027B中的combase.dll;发生了应用程序内部异常(参数:0x16E73128,0x00000001)."

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

预先感谢

推荐答案

有两种方法.
第一个是像您一样使用HttpClient(这对于小型文件非常有用)

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

第二个是使用 BackgroundDownloader类.推荐的方式

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);
        }
    }

这篇关于如何在C#中使用UWP下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆