当前位置:  编程技术>.net/c#/asp.net

C#同步、异步远程下载文件实例

    来源: 互联网  发布时间:2014-10-30

    本文导语:  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 =...

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

        ///
        /// 异步接受数据
        ///
        ///
        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


    
 
 

您可能感兴趣的文章:

  • C#同步和异步调用方法实例
  • c#同步两个子目录文件示例分享 两个文件夹同步
  • 解析C#中委托的同步调用与异步调用(实例详解)
  • c#线程同步的问题与实例分析
  • 基于C#实现的多生产者多消费者同步问题实例
  • c#(Socket)同步套接字代码的实例代码
  • c#(Socket)同步套接字代码示例
  • C#简单多线程同步和优先权用法实例
  • c#实现数据同步的方法(使用文件监控对象filesystemwatcher)
  • C# 委托的三种调用示例(同步调用 异步调用 异步回调)
  • C#应用BindingSource实现数据同步的方法
  • c#线程同步使用详解示例
  • 半同步/半异步的Tcp Server LightningServer
  • Jquery Ajax解析XML数据(同步及异步调用)简单实例
  • 使用异步方式调用同步方法(实例详解)
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • linux下指定mysql数据库服务器主从同步的配置实例
  • JAVA线程同步实例教程
  • win2003 安装2个mysql实例做主从同步服务配置
  • Linux下指定mysql数据库数据配置主主同步的实例
  • C++ I/O 成员 sync_with_stdio():同标准I/O同步
  • 除了用现成的线程同步函数之外,能否自己写线程同步函数?
  • python下用os.execl执行centos下的系统时间同步命令ntpdate
  • linux时钟为何与BIOS时钟不同步?如何使其同步?
  • Linux下时钟同步问题:Clock skew detected原因分析及解决方法
  • discuz免激活同步登入代码修改方法(discuz同步登录)
  • Linux下用ntpdate同步时间及date显示设置时间
  • 内核同步?
  • 跨平台的文件同步工具 Capivara
  • 信息同步工具 SyncMate
  • 高清视频同步播放控制器 HDSync
  • NTP时间同步
  • 如何在一段程序同步几个变量??
  • linux服务器之间如何实现时间同步?
  • 日历同步统计 GCALDaemon
  • 数据同步和复制解决方案 SymmetricDS
  • linux虚拟机时间与windows时间如何同步
  • 集群同步工具 Csync2
  • 目录同步工具 DirSync
  • 文件夹比较和同步工具 FreeFileSync
  • 关于邮件系统同步的问题,高手请进




  • 特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3