一切福田,不離方寸,從心而覓,感無不通。

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 = "保存成功!";
}
catch (Exception ex)
{
tb.Text = ex.Message;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>抓取网页图片并保存</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="tb" runat="server" Width="500" Height="300" TextMode="multiLine"></asp:TextBox>
</div>
</form>
</body>
</html>

转自:http://blog.sina.com.cn/s/blog_6edd55060100yptv.html