** 1. 首先界面大概是这样的**
界面并不是很复杂,两个Button打开OpenFileDialog和FolderBroswerDialog,最下面的控件是ProgressBar用于查看进度。
** 2. 然后思路大概是这样的**
- 首先获取需要复制文件的路径和文件名,还有目标位置的路径。
- 接着创建文件流,对文件进行读取。
- 最后将文件读取到目标位置。
** 3. 接着实现大概是这样的**
获取需要复制文件的路径和文件名,还有目标位置的路径。
private void btnSourse_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
textSource.Text = openFileDialog1.FileName;
}
private void btnTarget_Click(object sender, EventArgs e){
folderBrowserDialog1.ShowDialog();
textTarget.Text = folderBrowserDialog1.SelectedPath;
}
创建文件流并写到目标位置
private void CopyFile(string source,string target){
string fileName = Path.Combine(target, Path.GetFileName(source));
using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
{
using (FileStream fsWrite = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] bytes = new byte[1024 * 1024 * 1];//这里可以调节写入和读取的速度
int r = fsRead.Read(bytes, 0, bytes.Length);
while (r > 0)
{
fsWrite.Write(bytes, 0, r);
int current = (int)((Convert.ToDouble(fsWrite.Position) /Convert.ToDouble( fsRead.Length)) * 100);
progressBar1.Value = current;
r = fsRead.Read(bytes, 0, bytes.Length);
}
}
}
}
4. 最后就来运行一下
private void btnCopy_Click(object sender, EventArgs e)
{
CopyFile(textSource.Text, textTarget.Text);
}
但是问题也就随之而来了,当我们复制大文件的时候,问题就出现了,复制的过程中,整个窗口都会卡死(虽然ProgressBar依然在动)。这时候我们要用线程解决这种问题了。
代码增加
private void ShowPro(int value)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<int>(i => { progressBar1.Value=i; }), value);
}
else
{
this.progressBar1.Value = value;
}
}
代码修改
private void CopyFile(string source,string target)
{
string fileName = Path.Combine(target, Path.GetFileName(source));
using (FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read))
{
using (FileStream fsWrite = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] bytes = new byte[1024 * 1024 * 1];
int r = fsRead.Read(bytes, 0, bytes.Length);
while (r > 0)
{
fsWrite.Write(bytes, 0, r);
int current = (int)((Convert.ToDouble(fsWrite.Position) /Convert.ToDouble( fsRead.Length)) * 100);
ShowPro(current);//新增代码
progressBar1.Value = current;
r = fsRead.Read(bytes, 0, bytes.Length);
}
}
}
}
private void btnCopy_Click(object sender, EventArgs e)
{
Thread thread = new Thread(() => { CopyFile(textSource.Text, textTarget.Text); });
thread.IsBackground = true;
thread.Start();
}
好了,再次运行,是不是发现没有卡死的现象呢?