C#在進度條中顯示複製檔案的進度

來源:互聯網
上載者:User

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

【本文參考於網路,並加以修改,編譯通過】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.