我有一个程序,我写的是下载到文件。第二个文件不是必要的,只包括一些时间。如果未包含第二个文件,则会返回HTTP 404
错误。
现在,问题是当返回此错误时,它会结束整个程序。我想要的是继续该程序并忽略HTTP错误。所以,我的问题是如何从HTTP 404
请求中捕获WebClient.DownloadFile
错误?
这是当前使用的代码::
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;
}
答案 0 :(得分:17)
如果具体想要捕获错误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
}
}
}
答案 1 :(得分:12)
WebClient will throw a WebException。
try {
downloader.DownloadFile(videoAddress, videoPath);
}
catch (WebException ex) {
// handle it here
}
答案 2 :(得分:7)
将try
catch
放入foreach
循环中。
foreach (string[] i in textList)
{
try
{
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;
if(Download(videoAddress, videoPath) == false)
{
//Download failed. Do what you want to do.
}
textBox1.Text = textBox1.Text + @"Complete video for" + videoName;
if(Download(imgAddress, imgPath)== false)
{
//Download failed. Do what you want to do.
}
textBox1.Text = textBox1.Text + @"Complete img for" + videoName;
}
catch(Exception ex)
{
//Error like IO Exceptions, Security Errors can be handle here. You can log it if you want.
}
}
下载档案的私人功能
private bool Download(string url, string destination)
{
try
{
WebClient downloader = new WebClient();
downloader.DownloadFile(url, destination);
return true;
}
catch(WebException webEx)
{
//Check (HttpWebResponse)webEx.Response).StatusCode
// Or
//Check for webEx.Status
}
return false;
}
您可以查看WebException
状态。根据错误代码,您可以继续或中断。
阅读更多@ MSDN
<强>建议强>
+
。希望这适合你。
答案 3 :(得分:1)
在代码中使用try catch webexception检查它将包含http状态代码的Exception消息。
您可以清除异常并继续。
答案 4 :(得分:1)
您可以尝试使用此代码从WebException或OpenReadCompletedEventArgs.Error获取HTTP状态代码:
HttpStatusCode GetHttpStatusCode(System.Exception err)
{
if (err is WebException)
{
WebException we = (WebException)err;
if (we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
return response.StatusCode;
}
}
return 0;
}
答案 5 :(得分:0)
在循环中使用带有WebException的try {} catch {}块! Dunno您正在使用的IDE,但使用Visual Studio,您可以获得有关异常的大量信息:)
答案 6 :(得分:0)
正如其他写作一样,try-catch就足够了。
另一个提示是使用HTTP HEAD检查是否有任何内容(它比完整的HTTP GET更轻):
var url = "url to check;
var req = HttpWebRequest.Create(url);
req.Method = "HEAD"; //this is what makes it a "HEAD" request
WebResponse res = null;
try
{
res = req.GetResponse();
res.Close();
return true;
}
catch
{
return false;
}
finally
{
if (res != null)
res.Close();
}
答案 7 :(得分:0)
DownloadFileTaskAsync
将抛出异常,但也会创建一个空文件。至少可以说这可能令人困惑!我花了太长时间才意识到这个代码除了抛出异常外还会创建一个空文件:
await webClient.DownloadFileTaskAsync(new Uri("http://example.com/fake.jpg"), filename);
相反,我切换到了这个(DownloadDataTaskAsync
而不是File
):
var data = await webClient.DownloadDataTaskAsync(new Uri("http://example.com/fake.jpg"));
File.WriteAllBytes(filename, data);
*我不确定500行为,但肯定有404会这样做。
答案 8 :(得分:0)
我会像这样使用某物。
public void Test()
{
try
{
WebClient webClient = new WebClient();
webClient.DownloadString("");
}
catch (WebException webException)
{
if (int.TryParse(
Regex.Match(webException.Message, @"(?<=error:\s\()\d+(?=\))", RegexOptions.Multiline).Value,
out var result))
{
switch (result)
{
case 404:
Console.WriteLine("Error 404");
break;
case 500:
Console.WriteLine("Error 500");
break;
}
}
}
}