C#同步、异步远程下载文件实例
发布时间:2023-08-26 21:08:49
1、使用HttpWebRequest/HttpWebResonse和WebClient
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
if (!response.ContentType.ToLower().StartsWith("text/"))
{
//Value = SaveBinaryFile(response, FileName);
byte[] buffer = new byte[1024];
Stream outStream = System.IO.File.Create(FileName);
Stream inStream = response.GetResponseStream();
int l;
do
{
l = inStream.Read(buffer, 0, buffer.Length);
if (l > 0)
outStream.Write(buffer, 0, l);
}
while (l > 0);
outStream.Close();
inStream.Close();
}
2、使用WebClient
string url = "http://www.mozilla.org/images/feature-back-cnet.png";
WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(url,"C:\\temp\\feature-back-cnet.png");
3、异步下载例子
///summary
///异步分析下载
///summary
private void AsyncAnalyzeAndDownload(string url, string savePath)
{
this.uriString = url;
this.savePath = savePath;
#region 分析计时开始
count = 0;
count1 = 0;
freq = 0;
result = 0;
QueryPerformanceFrequency(ref freq);
QueryPerformanceCounter(ref count);
#endregion
using (WebClient wClient = new WebClient())
{
AutoResetEvent waiter = new AutoResetEvent(false);
wClient.Credentials = CredentialCache.DefaultCredentials;
wClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(AsyncURIAnalyze);
wClient.DownloadDataAsync(new Uri(uriString), waiter);
waiter.WaitOne(); 阻止当前线程,直到收到信号
}
}
///summary
///异步分析
///summary
protected void AsyncURIAnalyze(Object sender, DownloadDataCompletedEventArgs e)
{
AutoResetEvent waiter = (AutoResetEvent)e.UserState;
try
{
if (!e.Cancelled && e.Error == null)
{
string dnDir = string.Empty;
string domainName = string.Empty;
string uri = uriString;
获得域名 [url]httpwww.sina.com[url]
Match match = Regex.Match(uri, @((http(s)))+[w-.]+[^]);, RegexOptions.IgnoreCase
domainName = match.Value;
获得域名最深层目录 [url]httpwww.sina.commail[url]
if (domainName.Equals(uri))
dnDir = domainName;
else
dnDir = uri.Substring(0, uri.LastIndexOf(''));
dnDir += '';
获取数据
string pageData = Encoding.UTF8.GetString(e.Result);
Liststring urlList = new Liststring();
匹配全路径
match = Regex.Match(pageData, @((http(s)))+((()+[w-.]+()))+[w-.]+.+( + ImageType + )); , RegexOptions.IgnoreCase
while (match.Success)
{
string item = match.Value;
短路径处理
if (item.IndexOf(http) == -1 && item.IndexOf(https) == -1)
item = (item[0] == '' domainName dnDir) + item;
if (!urlList.Contains(item))
{
urlList.Add(item);
imgUrlList.Add(item);
实时显示分析结果
AddlbShowItem(item);
边分析边下载
WebRequest hwr = WebRequest.Create(item);
hwr.BeginGetResponse(new AsyncCallback(AsyncDownLoad), hwr);
hwr.Timeout = 0x30D40; 默认 0x186a0 - 100000 0x30D40 - 200000
hwr.Method = POST;
hwr.C;
hwr.MaximumAutomaticRedirections = 3;
hwr.Accept =imagegif, imagex-xbitmap, imagejpeg, imagepjpeg, applicationx-shockwave-flash, applicationvnd.ms-excel, applicationvnd.ms-powerpoint, applicationmsword, ;
hwr.Accept = imagegif, imagex-xbitmap, imagejpeg, imagepjpeg, ;
IAsyncResult iar = hwr.BeginGetResponse(new AsyncCallback(AsyncDownLoad), hwr);
iar.AsyncWaitHandle.WaitOne();
}
match = match.NextMatch();
}
}
}
finally
{
waiter.Set();
#region 分析计时结束
QueryPerformanceCounter(ref count1);
count = count1 - count;
result = (double)(count) (double)freq;
toolStripStatusLabel1.Text = 分析完毕!;
toolStripStatusLabel2.Text = string.Format( 分析耗时{0}秒, result);
Application.DoEvents();
#endregion
分析完毕
isAnalyzeComplete = true;
}
}
/// <summary>
/// 异步接受数据
/// </summary>
/// <param name="asyncResult"></param>
public void AsyncDownLoad(IAsyncResult asyncResult)
{
#region 下载计时开始
if (cfreq == 0)
{
QueryPerformanceFrequency(ref cfreq);
QueryPerformanceCounter(ref ccount);
}
#endregion
WebRequest request = (WebRequest)asyncResult.AsyncState;
string url = request.RequestUri.ToString();
try
{
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream stream = response.GetResponseStream())
{
Image img = Image.FromStream(stream);
string[] tmpUrl = url.Split('.');
img.Save(string.Concat(savePath, "/", DateTime.Now.ToString("yyyyMMddHHmmssfff"), ".", tmpUrl[tmpUrl.Length - 1]));
img.Dispose();
stream.Close();
}
allDone.Set();
//从未下载的列表中删除已经下载的图片
imgUrlList.Remove(url);
//更新列表框
int indexItem = this.lbShow.Items.IndexOf(url);
if (indexItem >= 0 && indexItem <= this.lbShow.Items.Count)
SetlbShowItem(indexItem);
}
catch (Exception)
{
imgUrlList.Remove(url);
}
}


猜你喜欢
- 本文实例为大家分享了Flutter Drawer抽屉菜单示例代码,供大家参考,具体内容如下一.Flutter Drawer组件简介1.源码查
- 基于这段时间折腾redis遇到了各种问题,想着整理一下。本文主要介绍基于Spring+Mybatis以注解的形式整合Redis。废话少说,进
- 这篇文章主要介绍了如何基于java语言实现八皇后问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友
- 面试题1:谈一下你对 Nginx 的理解Nginx 是一款自由的、开源的、高性能的 HTTP 服务器和反向代理服务器;同时也是一个 IMAP
- 最近,项目上涉及到了图像压缩,发现原有的图像压缩功能,虽然保证了图像的大小300K以内,但是压缩后的图像看的不在清晰,并且,限定了图片的He
- 今天看到EOE问答里面有这“[Android 界面]NotificationManager 如何使用Bitmap做图标”这样一个问题,在论坛
- 前言接着我上一章:Java Fluent Mybatis 项目工程化与常规操作详解流程篇 下上一章我把项目做了一部分工程化包装,主要还是想要
- 首先从表现层介绍,后续后深入原理。1、先简单介绍maven如何生成jar文件方便测试<plugin>
- 介绍环境配置Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEcl
- 写在前面注:本文章使用的 SpringBoot 版本为 2.2.4.RELEASE,其 Spring 版本为 5.2.3.RELEASE前言
- 字符串和列表学完,自己试着写了一个非常简单的Python名片管理系统。新萌尝试,大佬们不要喷。修改名片的功能我偷了个懒,因为我不知道怎么通过
- 原因如下: Delete()之后需要datatable.AccepteChanges()方法确认完全删除,因为Delete()只是将相应列的
- 答案是能!松哥之前写过类似的文章,但是主要是讲了用法,今天我们来看看原理!本文基于当前 Spring Security 5.3.4 来分析,
- 简介我们在前面的Android教程中已经提到过这么一件事:Android在启动后会有一个主线程。它不允许任何子线程去改变主UI线程里的内容。
- spring boot2.x已经出来好一阵了,而且spring cloud 的最新Release版本Finchley.RELEASE,默认集
- 在前一期中,我们做了悬浮头部的两个tab切换和下拉刷新效果,后来项目中要求改成三个tab,当时就能估量了一下,如果从之前的改,也不是不可以,
- 前言在讲述线程池的前提 先补充一下连接池的定义连接池是创建和管理一个连接的缓冲池的技术,这些连接准备好被任何需要它们的线程使用可以看到其连接
- Spring框架提供了事务管理的标准实现,且可以通过注解或者XML文件的方式声明和配置事务。通过异步事件的方式解耦服务调用,可以提高程序的响
- 本文实例讲述了C#启动进程的几种常用方法。分享给大家供大家参考。具体如下:1.启动子进程,不等待子进程结束private void simp
- spring.activemq.pool.enabled=false时,每发送一条数据都需要创建一个连接,这样会出现频繁创建和销毁连接的场景