C# WebClient上传下载时进度条显示,找了好久才找到的哦!

2、代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace WebClientUpload
{
    public partial class Form3 : Form
    {
        WebClient c;
        public Form3()
        {
            InitializeComponent();
            c = new System.Net.WebClient();
            c.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(c_DownloadProgressChanged);
            c.DownloadFileCompleted += new AsyncCompletedEventHandler(c_DownloadFileCompleted);
            c.Proxy = WebRequest.DefaultWebProxy;
            //c.Proxy.Credentials = new NetworkCredential("admin", "admin_password", "domain");

        }

        void c_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("ok");
            this.Close();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
          
        }

        void c_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            this.label1.Text = "已完成:" + progressBar1.Value.ToString()+"%";
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
          
        }


        private void Form3_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //上传文件
            c.DownloadFileAsync(new Uri("d:\\download\\阿甘正传.rm"), @"e:\11.rm");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //取消上传
            if (c != null)
            {
                c.CancelAsync();
            }
            Close();
        }
    }
}

 

 

 

附:另种进度条控制方案:

Form1调用 Form2(进度条窗体)         

   Form2 pj = new Form2();
            pj.Show();

            //开始处理大量耗时工作
            string sor = "";
            int j = 100000;
            for (int i = 0; i < j; i++)
            {
                sor += i.ToString();
                if (i % (j / 100) == 0)
                {
                    pj.progressBar1.Value++;
                    pj.label2.Text = "已完成:" + string.Format("{0:p}", (double)pj.progressBar1.Value / 100);
                    Application.DoEvents();
                }
            }
            //工作完成,关闭进度条窗体
            pj.Close();

你可能感兴趣的:(C++,c,windows,.net,C#)