Form1
FrFrm_Plan:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFile.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog floder = new FolderBrowserDialog();
if (floder.ShowDialog() == DialogResult.OK)
{
textBox2.Text = floder.SelectedPath;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0)
{
Frm_Plan F_Plan = new Frm_Plan();
F_Plan.filePath = textBox1.Text;
F_Plan.ToFile = textBox2.Text;
F_Plan.ShowDialog();
F_Plan.Dispose();
}
}
}
public partial class Frm_Plan : Form
{
public Frm_Plan()
{
InitializeComponent();
}
public string filePath = "";//源文件路径
public string ToFile = "";//目的文件的路径
int totalSize;//源文件的大小
int position = 0;//记录文件已复制的大小
const int BUFFER_SIZE = 4096;//每次复制的字节数
byte[] buffer;//记录复制的字节
Stream stream;//定义Stream类
FileStream fs;//定义FileStream类
private System.Threading.Thread thdAddFile; //创建一个线程
private void Frm_Plan_Shown(object sender, EventArgs e)
{
thdAddFile = new Thread(new ThreadStart(SetAddFile)); //创建一个线程
thdAddFile.Start(); //执行当前线程
}
public delegate void AddFile();//定义托管线程
/// <summary>
/// 设置托管线程
/// </summary>
public void SetAddFile()
{
this.Invoke(new AddFile(RunAddFile));//对指定的线程进行托管
}
/// <summary>
/// 设置线程
/// </summary>
public void RunAddFile()
{
CopyFile();
thdAddFile.Abort();//执行线程
}
public void CopyFile()
{
if (filePath.Length == 0 || ToFile.Length == 0)
Close();
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
totalSize = (int)fs.Length;
this.progressBar1.Maximum = totalSize;
stream = fs;
FileInfo fileInfo = new FileInfo(filePath);
ToFile += "\\" + fileInfo.Name;
if (File.Exists(ToFile))
File.Delete(ToFile);
if (totalSize > BUFFER_SIZE)
{
buffer = new byte[BUFFER_SIZE];
timer1.Start();
stream.BeginRead(buffer, 0, BUFFER_SIZE, new AsyncCallback(AsyncCopyFile), null);
}
else
{
fileInfo.CopyTo(ToFile, true);
position = totalSize;
fs.Close();
timer1.Start();
}
}
private void AsyncCopyFile(IAsyncResult ar)
{
int readedLength;
lock (stream)
{
readedLength = stream.EndRead(ar);
}
FileStream fsWriter = new FileStream(ToFile, FileMode.Append, FileAccess.Write);
fsWriter.Write(buffer, 0, buffer.Length);
fsWriter.Close();
position += readedLength;
if (position >= totalSize)
{
stream.Close();
return;
}
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 timer1_Tick(object sender, EventArgs e)
{
this.progressBar1.Value = position;
if (progressBar1.Value >= progressBar1.Maximum)
{
fs.Close();
timer1.Stop();
Close();
}
}
}