gpt4 book ai didi

c# - 如何检查 WebClient 请求是否有 404 错误

转载 作者:IT王子 更新时间:2023-10-29 04:47:07 26 4
gpt4 key购买 nike

我正在编写一个下载到文件的程序。第二个文件不是必需的,只是在某些时候包含在内。如果不包含第二个文件,它将返回一个 HTTP 404 错误。

现在,问题是当返回这个错误时,它结束了整个程序。我想要的是继续程序并忽略 HTTP 错误。所以,我的问题是如何从 WebClient.DownloadFile 请求中捕获 HTTP 404 错误?

这是当前使用的代码::

WebClient downloader = new WebClient();
foreach (string[] i in textList)
{
String[] fileInfo = i;
string videoName = fileInfo[0];
string videoDesc = fileInfo[1];
string videoAddress = fileInfo[2];
string imgAddress = fileInfo[3];
string source = fileInfo[5];
string folder = folderBuilder(path, videoName);
string infoFile = folder + '\\' + removeFileType(retrieveFileName(videoAddress)) + @".txt";
string videoPath = folder + '\\' + retrieveFileName(videoAddress);
string imgPath = folder + '\\' + retrieveFileName(imgAddress);
System.IO.Directory.CreateDirectory(folder);
buildInfo(videoName, videoDesc, source, infoFile);
textBox1.Text = textBox1.Text + @"begining download of files for" + videoName;
downloader.DownloadFile(videoAddress, videoPath);
textBox1.Text = textBox1.Text + @"Complete video for" + videoName;
downloader.DownloadFile(imgAddress, imgPath);
textBox1.Text = textBox1.Text + @"Complete img for" + videoName;
}

最佳答案

如果您特别想要捕获错误 404:

using (var client = new WebClient())
{
try
{
client.DownloadFile(url, destination);
}
catch (WebException wex)
{
if (((HttpWebResponse) wex.Response).StatusCode == HttpStatusCode.NotFound)
{
// error 404, do what you need to do
}
}
}

或者,使用 C# 7 或更高版本:

using (var client = new WebClient())
{
try
{
client.DownloadFile(url, destination);
}
catch (WebException ex) when
(ex.Response is HttpWebResponse wr && wr.StatusCode == HttpStatusCode.NotFound)
{
// error 404, do what you need to do
}
}

关于c# - 如何检查 WebClient 请求是否有 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8968641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com