也是比较老的东西了

最近用到

记录下以免以后忘了

要下载图片首先要有图片地址

要有图片地址就要先把网页下下来分析下URL

下载网页一般用两种方法

1,用 system.net.webclient


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

string url
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
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();
}



至于怎么找图片url略过,直接说下载图片吧

其实和上面一样,也有两种方法:

1,WebRequest和WebResponse


WebRequest request = WebRequest.Create
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 
string filepath = "x:\\pic.jpg";
WebClient mywebclient = new WebClient();
mywebclient.DownloadFile(url, filepath);


/// <summary>

/// 指定表头下载图片

/// </summary>

/// <param name="data"></param>

/// <param name="url"></param>

/// <returns></returns>

public void DownImg(string url, string imgUrl, string savePath)

{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);

request.Referer = url;

log.Info("这是原url地址" + url + "这是下载imgUrl地址" + imgUrl + "这是保存savePath路径" + savePath);

WebResponse response = request.GetResponse();

Stream reader = response.GetResponseStream();

FileStream writer = new FileStream(savePath, 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();

}