ASP.NET 抓取网页内容-图片

作者:vkvi 来源:千一网络(原创) 日期:2007-8-13

本文不仅适用于图片,同样实用于其它二进制文件。

需要四个类:WebRequest、WebResponse、Stream、FileStream。

WebRequest、WebResponse 的名称空间是:

System.Net

Stream、FileStream 的名称空间是:

System.IO

核心代码

WebRequest request = WebRequest.Create("http://www.cftea.com/images/logo.gif");
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();

FileStream writer = new FileStream("D:\\logo.gif", 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://www.cftea.com/images/logo.gif");
            WebResponse response = request.GetResponse();
            Stream reader = response.GetResponseStream();
           
            FileStream writer = new FileStream("D:\\logo.gif", 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>

相关阅读

你前面那位网友看了:ASP 中能用 StrComp 代替 LCase 执行忽略大小写的比较吗?

▲▲▲嘿,欢迎转载传播本站原创文章,尽量保留来源噢。▲▲▲

文章评论
  • 1 楼:评论
赞助商们