简体   繁体   English

C#WebClient下载空文件

[英]C# WebClient Downloads empty file

I'm working on an app that uses Bing's API to search and download images. 我正在开发一个使用Bing API搜索和下载图像的应用程序。 Bing's API provides a set of image links and I iterate over them and download each one. Bing的API提供了一组图像链接,我遍历了它们并下载了每个链接。

The problem that I'm having is that sometimes the downloaded file size is 0Kb. 我遇到的问题是,有时下载的文件大小为0Kb。 I assume that happens because WebClient first creates the filename and then tries to write to it. 我认为发生这种情况是因为WebClient首先创建文件名,然后尝试写入文件名。 So when it can't write to it for some reason this happens. 因此,当由于某种原因无法对其进行写入时,就会发生这种情况。 The problem is that it happens without throwing an exception so my 'Catch' statement can't catch this and delete the file. 问题是它发生时没有引发异常,因此我的“ Catch”语句无法捕获此异常并删除文件。

public void imageFetcher(string performerName, int maxNumberOfImages, RichTextBox richTextBox)
    {
        string performersDirPath = Environment.CurrentDirectory + @"\Performers\";
        string performerPath = performersDirPath + performerName + @"\";

        if (!Directory.Exists(performersDirPath))
        {
            Directory.CreateDirectory(performersDirPath);
        }

        if (!Directory.Exists(performerPath))
        {
            Directory.CreateDirectory(performerPath);
        }

        // Searching for Images using bing api
        IEnumerable<Bing.ImageResult> bingSearch = bingImageSearch(performerName);

        int i = 0;

            foreach (var result in bingSearch)
            {
                downloadImage(result.MediaUrl, performerPath + performerName + i + ".jpg",richTextBox);
                i++;
                if (i == maxNumberOfImages)
                {
                    break;
                }
            }
    }

The download method: 下载方法:

public void downloadImage(string imgUrl, string saveDestination, RichTextBox richTextBox)
    {
        if (File.Exists(saveDestination))
        {
            richTextBox.ForeColor = System.Drawing.Color.Red;
            richTextBox.AppendText("The File: " + saveDestination + "Already exists");

        }
        else
        {
            try
            {
                using (WebClient client = new WebClient())
                    {

                    client.DownloadFileCompleted += new AsyncCompletedEventHandler(((sender, e) => downloadFinished(sender, e, saveDestination , richTextBox)));
                    Uri imgURI = new Uri(imgUrl, UriKind.Absolute);

                    client.DownloadFileAsync(imgURI, saveDestination);
                    }
            }
            catch (Exception e)
            {
                richTextBox.AppendText("There was an exception downloading the file" + imgUrl);
                richTextBox.AppendText("Deleteing" + saveDestination);
                File.Delete(saveDestination);
                richTextBox.AppendText("File deleted!");

            }

        }

    }

This happens also when I try to wait for the client to finish using: 当我尝试等待客户端完成使用时,也会发生这种情况:

client.DownloadFileAsync(imgURI, saveDestination);

                        while (client.IsBusy)
                        {

                        }

Can anyone please tell me what I'm doing wrong? 谁能告诉我我在做什么错?

In other simular question the solution was to keep the Webclient instance open until download is finished.. I'm doing this with this loop: 在另一个类似的问题中,解决方案是保持Webclient实例处于打开状态,直到下载完成。.我正在执行以下循环:

while (client.IsBusy){}

Yet the results are the same. 然而结果是一样的。

Update: I resorted to not use webclient, instead I used this code: 更新:我不使用webclient,而是使用以下代码:

try
                        {
                            byte[] lnBuffer;
                            byte[] lnFile;

                            using (BinaryReader lxBR = new BinaryReader(stream))
                            {
                                using (MemoryStream lxMS = new MemoryStream())
                                {
                                    lnBuffer = lxBR.ReadBytes(1024);
                                    while (lnBuffer.Length > 0)
                                    {
                                        lxMS.Write(lnBuffer, 0, lnBuffer.Length);
                                        lnBuffer = lxBR.ReadBytes(1024);
                                    }
                                    lnFile = new byte[(int)lxMS.Length];
                                    lxMS.Position = 0;
                                    lxMS.Read(lnFile, 0, lnFile.Length);
                                }

using (System.IO.FileStream lxFS = new FileStream(saveDestination, FileMode.Create))
                                    {

                                        lxFS.Write(lnFile, 0, lnFile.Length);
                                    }

This solves the problem almost complelty, there are still one or two 0KB files but I assume it's because of network errors. 这几乎解决了这个问题,仍然有一个或两个0KB文件,但我认为是由于网络错误。

To see possible exceptions - try changing DownloadFileAsync to just DownloadFile - my problem was "Can not create SSL/TLS secure channel". 要查看可能的异常-尝试将DownloadFileAsync更改为DownloadFile-我的问题是“无法创建SSL / TLS安全通道”。 Hope this will help someone. 希望这会帮助某人。

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

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