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;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
//线程不安全做法
//Control.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(() =>
{
//采集数据
string source = textBox2.Text.Trim();
string target = textBox1.Text.Trim();
CopyFile(source, target);
}));
t.IsBackground = true;
t.Start();
}
/// <summary>
/// 拷贝
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
private void CopyFile(string source, string target)
{
progressBar1.Maximum = 100;
progressBar1.Minimum = 0;
using (FileStream fsRead = File.OpenRead(source))
{
using (FileStream fsWrite = File.OpenWrite(target))
{
byte[] buffers = new byte[1024 * 1024 * 5];
int r = fsRead.Read(buffers, 0, buffers.Length);
while (r > 0)
{
fsWrite.Write(buffers, 0, r);
//计算拷贝了多少(计算百分百,然后显示到进度条上)
int percent = (int)(fsWrite.Position * 1.0 / fsRead.Length * 100);
if (percent >= 100)
{
percent = 100;
}
//跨线程访问控件
//progressBar1.Value = percent;
progressBar1.Invoke(new Action<int>(p =>
{
progressBar1.Value = p;
}), percent);
r = fsRead.Read(buffers, 0, buffers.Length);
}
}
}
}
}
}