c# - Webclient 没有下载图片
问题描述
我正在使用 C# Webclient 下载图像,但是有一个问题,因为图像是 0 kb。
在此过程中,我没有收到错误消息。
有人能帮我吗?
谢谢
private static void Download(string _caminhoArquivo, string _nomeArquivo)
{
try
{
using (WebClient client = new WebClient())
{
string _arquivodownl = "C:\\Img\\ImagensMensagens\\" + _nomeArquivo;
string url = "https://p2.trrsf.com/image/fget/cf/940/0/images.terra.com/2020/10/16/2020-10-16T140412Z_1_LYNXMPEG9F1AV_RTROPTP_4_BRAZIL-POLITICS.JPG";
client.DownloadFileAsync(new Uri(url), _arquivodownl);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
解决方案
您正在调用DownloadFileAsync
,这是一种非阻塞方法,这意味着它将在文件完全下载之前完成。
你有两个选择:
1-将代码更改为同步:
client.DownloadFile(new Uri(url), _arquivodownl);
这样,该功能将在下载文件后完成。
2-挂钩DownloadFileCompleted
事件:
client.DownloadFileCompleted += (o, e) => { /* Process here the file */ }
client.DownloadFileAsync(new Uri(url), _arquivodownl);
DownloadFileCompleted
这将在文件下载完成后引发事件。您可以将事件挂钩到函数,我将它挂钩到 lambda 只是作为示例。此外,您应该检查e.Cancelled
并e.Error
确保下载成功。
第二种方法的好处是不会阻止您的应用程序等待下载结束。
此外,如果您使用第二种方法,则必须删除 ,using
否则您将WebClient
在文件下载之前处理掉 。
推荐阅读
- arrays - Postgres SQL向所有json数组添加键
- cognos - Cognos Analytics 11.x:如何默认为所有用户“预览无数据”
- python - 处理 foxpro dbf 文件中已删除记录的问题
- xml - 如何使用 Perl 将生成的文本文件转换为 Junit 格式(XML)
- python - 存储在单独数据帧中的值之间的线性插值
- node.js - expressjs 模式以匹配路径的其余部分
- sql - 在 FileMaker Pro 中修改 ExecuteSQL 语句以允许天宽
- angular - 是否可以将 FormData 与图像文件一起从 Angular 6 应用程序发送到 Web API
- python - 不使用坐标的触摸和拖动:Squish 版本 [6.4.1]
- laravel - Laravel 响应下载在路由中间件和前缀中不起作用