zoukankan      html  css  js  c++  java
  • 多线程实现文件复制

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

    namespace CopyFileDemo
    {
        public partial class CopyProgressForm : Form
        {
            string destFile, srcFile;

            public CopyProgressForm(string destFile, string srcFile)
            {
                InitializeComponent();
                Control.CheckForIllegalCrossThreadCalls = false;

                this.destFile = destFile;   // 要复制的源文件名称
                this.srcFile = srcFile;     // 要复制到的目标文件名称
            }

            private void CopyProgressForm_Load(object sender, EventArgs e)
            {
                this.Show();

                // 在此处创建多线程复制文件
                Thread thread = new Thread(new ThreadStart(this.CopyProcess));
                thread.IsBackground = true;
                thread.Start();
            }

            void CopyProcess()
            {
                FileStream src = null,dest = null;

                try
                {
                    src = new FileStream(this.srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                    dest = new FileStream(this.destFile, FileMode.Create, FileAccess.Write, FileShare.None);

                    long size = src.Length;
                    long currBytes = 0;
                    byte[] buffer = new byte[1024];
                    int length = 0;

                    do
                    {
                        length = src.Read(buffer, 0, buffer.Length);
                        currBytes += length;
                        this.pgrProgress.Value = (int)(currBytes * 100 / size);

                        dest.Write(buffer, 0, length);
                    }
                    while (length != 0);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (src != null)
                        src.Close();
                    if (dest != null)
                        dest.Close();

                    this.Close();
                }
            }

            private void btnCancel_Click(object sender, EventArgs e)
            {
                this.Close();
            }
        }
    }

  • 相关阅读:
    老毛桃PE修改方法(屏蔽更改主页,屏蔽加装的绿色浏览器)
    老毛桃winpe优盘启动系统个性修改全攻略
    SQL2000和SQL2005和SQL2008同时安装问题
    基于FFmpeg的音频编码(PCM数据编码成AAC android)
    springboot + mybatis +easyUI整合案例
    spring thymeleaf 自定义标签
    速度挑战
    兼顾pc和移动端的textarea字数监控的实现方法
    CSS3+JS 实现的便签应用
    JavaScript实现碰撞检测(分离轴定理)
  • 原文地址:https://www.cnblogs.com/lds85930/p/1173817.html
Copyright © 2011-2022 走看看