本想自己写程序,将网络上大量的图片下载到本地,那么就得先得到网络上的图片地址,
每个网页,可能都有一些图片,为了下载 整个页面的图片,
需要先下载整个网页,从网页中,找到图片地址。
下载网页一般使用以下两种方法:
1:使用:System.Net.WebClient
public static void DownloadFile(string sourceUri, string filePath)
{
WebClient client = new WebClient();
string path = "C:\\wendang\\";
try
{
client.DownloadFile(sourceUri, path + filePath);
}
catch (Exception ex)
{
return;
}
}
2:使用:System.Net.HttpWebRequest
using System.Net;
using System.IO;
using System.Windows.Forms;
public void GetFile()
{
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)
{
return;
}
finally
{
if (reader != null)
reader.Close();
if (response != null)
response.Close();
}
}
找到网页内容,从中找到图片地址,将图片下载到本地
下载图片实际案例
1:WebRequest和WebResponse
public static void GetFile()
{
string url = "http://images.cnblogs.com/logo_small.gif";
WebResponse response = null;
Stream reader = null;
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
response = request.GetResponse();
reader = response.GetResponseStream();
FileStream write = new FileStream("E:\\pic.jpg", FileMode.OpenOrCreate, FileAccess.Write);
byte[] buff = new byte[512];
int c = 0;//实际读取的字节数
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
write.Write(buff, 0, c);
}
write.Close();
write.Dispose();
reader.Close();
reader.Dispose();
response.Close();
}
catch (Exception ex)
{
return;
}
}
2:WebClient
public static void GetFileByWebClient()
{
try
{
string url = "http://images.cnblogs.com/logo_small.gif";
string filepath = "E:\\picg.jpg";
WebClient mywebclient = new WebClient();
mywebclient.DownloadFile(url, filepath);
}
catch (Exception)
{
return;
}
}