从网络下载图片文件到本地

本想自己写程序,将网络上大量的图片下载到本地,那么就得先得到网络上的图片地址,
每个网页,可能都有一些图片,为了下载 整个页面的图片,
需要先下载整个网页,从网页中,找到图片地址。
下载网页一般使用以下两种方法:

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;
        }
    }

转载于:https://www.cnblogs.com/weiqinl/p/5441462.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值