zoukankan      html  css  js  c++  java
  • WPF 下载网络文件 带进度条

     

    使用
            private void Button_Click_1(object senderRoutedEventArgs e)
            {
                string url = "http://files.cnblogs.com/xe2011/WpfApplication1_webbrowser_transparent.rar";
                bool b =DownloadFile(url@"D:AdministratorDesktop123.7z"progressBar1label1);
                if (b)
                    MessageBox.Show("下载成功");
                else
                    MessageBox.Show("下载失败");
            }
     

            public bool DownloadFile(string URLstring fileNameSystem.Windows.Controls.ProgressBar progressBar1)
            {
                try
                {
                    System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                    System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();
     
                    long totalLength = httpWebResponse1.ContentLength;
                    if (progressBar1 != null)
                    {
                        progressBar1.Maximum = (int)totalLength;
                    }
                    System.IO.Stream stream1 = httpWebResponse1.GetResponseStream();
                    System.IO.Stream stream2 = new System.IO.FileStream(fileNameSystem.IO.FileMode.Create);
                    
                    long currentLength = 0;
                    byte[] by = new byte[1024];
                    int osize = stream1.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        WpfApplication.DispatcherHelper.DoEvents();
                        
                        currentLength = osize + currentLength;
                        stream2.Write(by, 0, osize);
                        if (progressBar1 != null)
                        {
                            progressBar1.Value = (int)currentLength;
                            label1.Content = String.Format("{0} / {1}"BytesToString(currentLength), BytesToString(totalLength));
                        }
                        osize = stream1.Read(by, 0, (int)by.Length);
                    }
                    
                    stream2.Close();
                    stream1.Close();
     
                    return (currentLength == totalLength); 
                }
                catch 
                {
                    return false;
                }
            }





    附件列表

  • 相关阅读:
    《.NET分布式应用程序开》读书笔记 第一章:理解分布式架构
    一个DataSet的工具类,可以将DataTime的Time部分去掉,主要在序列化Xml时有用.
    Microsoft SQL Server 2005技术内幕系列书籍
    COM+客户端部署发现
    PowerDesigner中三种模型的转换关系图
    将ASP.NET页面内容输出到字符串中
    在WinForms中隐藏Crystal Report的[MainReport]标签页
    qmake常用语法一
    MinGW简介
    Qt的prx文件
  • 原文地址:https://www.cnblogs.com/xe2011/p/3761963.html
Copyright © 2011-2022 走看看