我正在开发一个使用 Bing 的 API 来搜索和下载图像的应用程序。Bing 的 API 提供了一组图像链接,我遍历它们并下载每个链接。
我遇到的问题是有时下载的文件大小为 0Kb。我假设发生这种情况是因为 WebClient 首先创建文件名,然后尝试写入它。因此,当它由于某种原因无法写入时,就会发生这种情况。问题是它发生时没有抛出异常,所以我的“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;
}
}
}
下载方式:
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!");
}
}
}
当我尝试等待客户端完成使用时也会发生这种情况:
client.DownloadFileAsync(imgURI, saveDestination);
while (client.IsBusy)
{
}
谁能告诉我我做错了什么?
在其他类似的问题中,解决方案是让 Webclient 实例保持打开状态,直到下载完成。我正在使用这个循环执行此操作:
while (client.IsBusy){}
然而结果是一样的。
更新:我不使用 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);
}
这几乎完全解决了问题,仍然存在一两个 0KB 文件,但我认为这是因为网络错误。