ASP.NET 抓取网页内容-图片
本文不仅适用于图片,同样实用于其它二进制文件。
需要四个类:WebRequest、WebResponse、Stream、FileStream。
WebRequest、WebResponse 的名称空间是:
System.Net
Stream、FileStream 的名称空间是:
System.IO
核心代码
WebRequest request = WebRequest.Create("http://portrait7.sinaimg.cn/1859998982/blog/180.jpg");
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream writer = new FileStream("D:\\logo.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();
注意类 Stream,不是 StreamReader。
示例
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
try
{
WebRequest request = WebRequest.Create("http://portrait7.sinaimg.cn/1859998982/blog/180.jpg");
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream writer = new FileStream("D:\\logo.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();
tb.Text = "保存成功!";
}