gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:25:34 24 4
gpt4 key购买 nike

我是编程初学者,我想知道在 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();
}
}

异常(exception)情况是:“0x750F6D7E 处的未处理异常(program.exe 0xC000027B 中的 combase.dll;发生应用程序内部异常(参数:0x16E73128、0x00000001)。”

提前致谢

最佳答案

有两种方法可以做到。
第一个是像你一样使用 HttpClient(这适用于小文件)

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

 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# - 如何在c#中使用UWP下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37806178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com