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


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

posted on 2009-12-23 20:40  GT_Andy  阅读(5116)  评论(0编辑  收藏  举报