【问题标题】:Webclient is not downloading the imageWebclient 没有下载图片
【发布时间】:2020-10-17 16:56:51
【问题描述】:

我正在使用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# .net webclient


    【解决方案1】:

    您正在调用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

    【讨论】:

    • 错过了3rd option - 使用HttpClient 而不是古老的WebClient 并让下载真正成为async
    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多