C#在进度条中显示复制文件的进度

C#。NET 程序设计 专栏收录该内容
61 篇文章 0 订阅

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Collections;
using System.Reflection;
using System.Threading;

namespace CopyForm
{
    public partial class frmMain : Form
    {
        int totalSize;
        int position;
        const int BUFFER_SIZE = 4096;
        byte[] buffer;
        Stream stream;

        public frmMain()
        {
            InitializeComponent();
        }

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

        private void btnCopy_Click(object sender, EventArgs e)
        {
            string strFile = "";
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                strFile = dlg.FileName;
            }
            else
            {
                return;
            }

            FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read);
            totalSize = (int)fs.Length;
            stream = fs;

            //Delete file which aready exists.
            if (File.Exists("c://CopyFile.bin"))
            {
                File.Delete("c://CopyFile.bin");
            }

            //Copy file while larger than 4KB.
            if (totalSize > BUFFER_SIZE)
            {
                buffer = new byte[BUFFER_SIZE];

                // Async Invoke
                stream.BeginRead(buffer, 0, BUFFER_SIZE, new AsyncCallback(AsyncCopyFile), null);
                MessageBox.Show("文件拷贝完毕!");
            }
            else
            {
                fs.Close();
            }
        }

        /// <summary>
        /// Asynchronously copy file
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncCopyFile(IAsyncResult ar)
        {
            int readenLength;

            //Lock FileStream
            lock (stream)
            {
                // When stream endread, get readed length
                readenLength = stream.EndRead(ar);
            }

            // Write to disk
            FileStream fsWriter = new FileStream("c://CopyFile.bin", FileMode.Append, FileAccess.Write);
            fsWriter.Write(buffer, 0, buffer.Length);
            fsWriter.Close();

            // Current stream position
            position += readenLength;
       
            // Response UI
            MethodInvoker m = new MethodInvoker(SynchProgressBar);
            m.BeginInvoke(null, null);

            if (position >= totalSize)  //read over
            {
                stream.Close();
                return;
            }

            // Continue to read and write
            lock (stream)
            {
                int leftSize = totalSize - position;

                if (leftSize < BUFFER_SIZE)
                {
                    buffer = new byte[leftSize];
                }
                stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(AsyncCopyFile), null);
            }
        }

        private void SynchProgressBar()
        {
            this.progressBar1.Minimum = 0;
            //this.progressBar1.Maximum = totalSize;
            //this.progressBar1.Value = position;
            SetControlPropertyValue(this.progressBar1, "Maximum", totalSize);
            SetControlPropertyValue(this.progressBar1, "Value", position);
        }

        /// <summary>
        /// Cross-thread operation not valid: (solution key)
        /// Control 'progressBar1' accessed from a thread other than the thread it was created on
        /// </summary>
        /// <param name="oControl"></param>
        /// <param name="propName"></param>
        /// <param name="propValue"></param>
        delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
        private void SetControlPropertyValue(Control oControl, string propName, object propValue)
        {
            if (oControl.InvokeRequired)
            {
                SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
                oControl.Invoke(d, new object[] { oControl, propName, propValue });
            }
            else
            {
                Type t = oControl.GetType();
                PropertyInfo[] props = t.GetProperties();
                foreach (PropertyInfo p in props)
                {
                    if (p.Name.ToUpper() == propName.ToUpper())
                    {
                        p.SetValue(oControl, propValue, null);
                    }
                }
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}


【本文参考于网络,并加以修改,编译通过】

  • 0
    点赞
  • 0
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值