【C#】下载网页及图片

转自: http://www.cnblogs.com/sun8134/archive/2010/07/05/1771187.html

下载网页一般用两种方法

1. 用 system.net.webclient

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

string url = "http://www.cnblogs.com";
string result = null;
try
{
    WebClient client = new WebClient();
    result = client.DownloadString( url );
}
catch (Exception ex)
{
    MessageBox.Show( ex.Message );
}


2. 用 System.Net.HttpWebRequest

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

string result = null;
string url = "http://www.cnblogs.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)
{
    MessageBox.Show( ex.Message );
}
finally
{
    if (reader != null)
        reader.Close();
    if (response != null)
        response.Close();
}
 
下载图片也有两种方法:

1. WebRequest和WebResponse

WebRequest request = WebRequest.Create("http://images.cnblogs.com/logo_small.gif");
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream writer = new FileStream("x:\\pic.jpg", FileMode.OpenOrCreate, FileAccess.Write);
byte[] buff = new byte[512];
int c = 0; //实际读取的字节数
while ((c=reader.Read(buff, 0, buff.Length)) > 0)
{
    writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
response.Close();


2. WebClient

string url = "http://images.cnblogs.com/logo_small.gif";
string filepath = "x:\\pic.jpg";
WebClient mywebclient = new WebClient();
mywebclient.DownloadFile(url, filepath);


你可能感兴趣的:(C#)