简体   繁体   English

如何在c#中使用UWP下载文件

[英]How to download files using UWP in c#

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: 我是编程的初学者,我想知道在UWP中下载文件的正确方法我现在使用它,但它只有50%的时间工作:

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)." 例外情况是:“0x750F6D7E处的未处理异常(program.exe 0xC000027B中的combase.dll;发生了应用程序内部异常(参数:0x16E73128,0x00000001)。”

Thanks in advance 提前致谢

There are two ways to do it. 有两种方法可以做到这一点。
First one is to use HttpClient as you do (this works well with small files) 第一个是像你一样使用HttpClient(这适用于小文件)

Second one is to use BackgroundDownloader Class . 第二个是使用BackgroundDownloader类 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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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