用C#读取网页(Read a Web Page in C#)

本文介绍两种使用C#从互联网上读取网页内容的方法。第一种方法利用System.Net.WebClient类的DownloadString方法轻松获取网页;第二种方法采用System.Net.HttpWebRequest类,通过HTTP与服务器直接交互,兼容性更佳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用C#读取网页

本文地址:

发布于

此文为翻译: 

原文地址:http://www.devtopics.com/read-a-web-page-in-c/

在c#中可以很容易的使用system.net.webclient 类来获取一个网页内容:

 

using  System.Net;
using  System.Windows.Forms;

string  url  =   " http://www.devtopics.com " ;
string  result  =   null ;

try
{
    WebClient client 
=   new  WebClient();
    result 
=  client.DownloadString( url );
}
catch  (Exception ex)
{
    
//  handle error
    MessageBox.Show( ex.Message );
}

获取到的网页内容保存到'Result'字符串中。注意:传给DownloadString函数的参数必须是以http://开头,否则它将报一个WebException异常。

另一种方法是使用System.Net.HttpWebRequest 类,它的兼容性更好,因为它直接使用http和服务器通讯。

 

using  System.Net;
using  System.IO;
using  System.Windows.Forms;

string  result  =   null ;
string  url  =   " http://www.devtopics.com " ;
WebResponse response 
=   null ;
StreamReader reader 
=   null ;

try
{
    HttpWebRequest request 
=  (HttpWebRequest)WebRequest.Create( url );
    request.Method 
=   " GET " ;
    response 
=  request.GetResponse();
    reader 
=   new  StreamReader( response.GetResponseStream(), Encoding.UTF8 );
    result 
=  reader.ReadToEnd();
}
catch  (Exception ex)
{
    
//  handle error
    MessageBox.Show( ex.Message );
}
finally
{
    
if  (reader  !=   null )
        reader.Close();
    
if  (response  !=   null )
        response.Close();
}
本文地址:
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值