我是C#的新手,正在处理从Web上抓取URL的窗口应用程序。应用程序需要Internet连接才能从Internet收集URL。问题是当没有互联网连接时发生。并且应用程序显示此类型的错误。
未处理的类型' System.Net.WebException'发生在 System.dll附加信息:远程名称不可能 已解决:' www.google.com'
问题是我写的那段代码告诉用户,没有互联网连接。而不是显示这种类型的Bug。 这是我正在处理的代码。
listBox1.Items.Clear();
StringBuilder sb = new StringBuilder();
byte[] ResultsBuffer = new byte[8192];
string SearchResults = "http://www.google.com/search?num=1000&q=" + txtKeyWords.Text.Trim();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
string sbb = sb.ToString();
HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.OptionOutputAsXml = true;
html.LoadHtml(sbb);
HtmlNode doc = html.DocumentNode;
foreach (HtmlNode link in doc.SelectNodes("//a[@href]"))
{
//HtmlAttribute att = link.Attributes["href"];
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
}
答案 0 :(得分:0)
您可以这样做:
//Include everything that could possibly throw an exception in the try brackets
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
catch (Exception e) // Here we are catching your bug-the unhandled exception
{
MessageBox.Show("You do not have an internet connection");
}
这就是为什么我的答案不完整,需要您做更多工作的原因:除了没有互联网,您可以收到更多例外情况。这个尝试捕获将捕获所有这些。您需要找到所有可能的异常并相应地处理它。
答案 1 :(得分:0)
首先尝试根据您的错误捕获特殊异常,然后针对可能发生的任何其他错误进行常规捕获,check out this和this
try
{
//your code here
}
catch (WebException ex)
{
MessageBox.Show("No internet available");
}
catch (Exception ex)
{
MessageBox.Show("Error has occured");
}