首页 > 解决方案 > 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);
            }
        }

标签: c#.netwebclient

解决方案


您正在调用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.Cancellede.Error确保下载成功。

第二种方法的好处是不会阻止您的应用程序等待下载结束。

此外,如果您使用第二种方法,则必须删除 ,using否则您将WebClient在文件下载之前处理掉 。


推荐阅读