2012-10-07 17 views
3

在C#控制檯應用程序中,我需要捕獲出「Internet無法顯示網頁」,然後我可以把我的支票。如果互聯網瀏覽器打開網址意味着互聯網連接在那裏,否則連接關閉。我使用下面的代碼在C#中的Webclient類輸出

WebClient client = new WebClient(); 
     string value = client.DownloadString("http://foo.com"); 
     Console.WriteLine(value.Length); 
     Console.WriteLine(value); 
     Console.WriteLine("Press any key to continue"); 

     Console.ReadKey(true); 

請SE中的方法來捕獲輸出

回答

0
WebClient client = new WebClient(); 
string value; 

try 
{ 
    value = client.DownloadString("http://foo.com"); 
} 
catch (WebException ex) 
{ 
    value = ex.Message; 
} 

Console.WriteLine(value.Length); 
Console.WriteLine(value); 
Console.WriteLine("Press any key to continue"); 
Console.ReadKey(true); 
+0

value = ex.ex.Message); 這是給出錯誤 – Sohail

+0

@Shahail請原諒打字錯誤。請參閱編輯的文章 –

+0

請注意,您可以從異常中獲得有關失敗請求的更多信息。有關更多詳細信息,請參閱[文檔](http://msdn.microsoft.com/zh-cn/library/system.net.webexception.aspx)。 –