大文件的拷贝(单线程)

2018-12-15  本文已影响1人  lizg

利用FileStream可进行大文件的拷贝操作,例如在窗体上拖动两个testbox和一个progressbar以及一个button,在Formload事件中对进度条初始化,点击button开始拷贝。

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

namespace 大文件拷贝
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitialProgressBar();
        }

        private void InitialProgressBar()
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string sourceFile = tbx_source.Text.Trim();
            string targetFile = tbx_target.Text.Trim();
            BigFileCopy(sourceFile,targetFile);
            
        }

        private void BigFileCopy(string sourceFile, string targetFile)
        {
            using (FileStream fsReader = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream fsWriter =new FileStream(targetFile,FileMode.Create,FileAccess.Write))
                {
                    byte[] array = new byte[1024 * 1024];
                    int count = fsReader.Read(array, 0, array.Length);
                    while (count>0)
                    {
                        fsWriter.Write(array, 0,count);
                        progressBar1.Value = (int)(fsReader.Position*1.0 / fsReader.Length*100);
                        count=fsReader.Read(array, 0, array.Length);
                    }
                    MessageBox.Show("文件拷贝成功!");
                }
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读