c# 下载网页图片

简介:

也是比较老的东西了

最近用到

记录下以免以后忘了

要下载图片首先要有图片地址

要有图片地址就要先把网页下下来分析下URL

下载网页一般用两种方法

1,用 system.net.webclient

using System.Net;
using System.Windows.Forms;

string url = "http://www.cnblogs.com";
string result = null;

try
{
    WebClient client = new WebClient();
    result = client.DownloadString( url );
}
catch (Exception ex)
{
    MessageBox.Show( ex.Message );
}

2,用 System.Net.HttpWebRequest

 

using System.Net;
using System.IO;
using System.Windows.Forms;

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)
{
    MessageBox.Show( ex.Message );
}
finally
{
    if (reader != null)
        reader.Close();
    if (response != null)
        response.Close();
}

 

 

至于怎么找图片url略过,直接说下载图片吧

其实和上面一样,也有两种方法:

1,WebRequest和WebResponse

WebRequest request = WebRequest.Create("http://images.cnblogs.com/logo_small.gif");
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream writer = new FileStream("x:\\pic.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();

 

2,WebClient

 

string url = "http://images.cnblogs.com/logo_small.gif";
string filepath = "x:\\pic.jpg";
WebClient mywebclient = new WebClient();
mywebclient.DownloadFile(url, filepath);



本文转自 sun8134 博客园博客,原文链接:http://www.cnblogs.com/sun8134/archive/2010/07/05/1771187.html   ,如需转载请自行联系原作者


相关文章
|
3天前
|
网络安全 C#
C# HttpWebRequest 获取 HTTPS 网页内容
C# HttpWebRequest 获取 HTTPS 网页内容
10 0
|
5天前
|
存储 算法 C#
C# 生成指定图片的缩略图
C# 生成指定图片的缩略图
|
5天前
|
C# 开发工具 数据安全/隐私保护
C# 给图片添加文字水印
C# 给图片添加文字水印
|
5天前
|
开发框架 .NET C#
C# 自动填充文字内容到指定图片
C# 自动填充文字内容到指定图片
|
2月前
|
数据采集 API C#
网页解析高手:C#和HtmlAgilityPack教你下载视频
使用C#和HtmlAgilityPack解析小红书网页,下载其视频内容。文章涵盖了解析网页、获取视频链接、C#实现、HtmlAgilityPack简化解析、代理IP确保下载稳定及多线程提高下载效率。提供的代码示例展示了如何设置代理和多线程下载视频。实验结果显示,该方法能有效、高效地下载小红书视频。
网页解析高手:C#和HtmlAgilityPack教你下载视频
|
2月前
|
API C# 数据安全/隐私保护
C# 实现网页内容保存为图片并生成压缩包
C# 实现网页内容保存为图片并生成压缩包
|
5月前
|
API C#
C# 调用系统“API“设置图片为“桌面壁纸“
C# 调用系统“API“设置图片为“桌面壁纸“
|
20天前
|
开发框架 前端开发 .NET
C#编程与Web开发
【4月更文挑战第21天】本文探讨了C#在Web开发中的应用,包括使用ASP.NET框架、MVC模式、Web API和Entity Framework。C#作为.NET框架的主要语言,结合这些工具,能创建动态、高效的Web应用。实际案例涉及企业级应用、电子商务和社交媒体平台。尽管面临竞争和挑战,但C#在Web开发领域的前景将持续拓展。
|
20天前
|
SQL 开发框架 安全
C#编程与多线程处理
【4月更文挑战第21天】探索C#多线程处理,提升程序性能与响应性。了解C#中的Thread、Task类及Async/Await关键字,掌握线程同步与安全,实践并发计算、网络服务及UI优化。跟随未来发展趋势,利用C#打造高效应用。