资源说明:大文件拷贝实例源码,学习关于IO文件流、多线程相关使用做参考。
private void button4_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0;
this.label1.Text = "0%";
if (!File.Exists(this.textBox1.Text))
{
MessageBox.Show("找不到目标文件!");
return;
}
if (!Directory.Exists(this.textBox2.Text))
{
MessageBox.Show("请选择有效的保存路径!");
return;
}
string fileRead = this.textBox1.Text;
string fileSave = Path.Combine(this.textBox2.Text, _fileName);
System.Threading.ThreadPool.QueueUserWorkItem((o) =>
{
using (IDisposable file = new FileStream(fileRead, FileMode.Open, FileAccess.Read),
fileWrite = new FileStream(fileSave, FileMode.Create, FileAccess.Write))
{
int count = 0;
long fileLength =((FileStream)file).Length; //目标文件大小
//根据目标文件大小创建byte数组长度
byte[] data = new byte[fileLength > 1024 * 1024 * 30 ? 1024 * 1024 * 30 : fileLength]; //30M 1024 * 1024 * 30
int step = (int)Math.Ceiling(fileLength * 1.0 / data.Length); //分流段数
double n = (100 * 1.0 / step); //每次进度条累加
double m = 0; //累加统计
int spam = 1; //时间间隔
double speed = 0; //拷贝速度
do
{
DateTime time = DateTime.Now;
//文件流操作
count = ((FileStream)file).Read(data, 0, data.Length);
((FileStream)fileWrite).Write(data, 0, count);
//保存时间间隔,单位毫秒
spam = (DateTime.Now - time).Milliseconds > 0 ? (DateTime.Now - time).Milliseconds : spam;//必须大于0
//计算速度 单位k/s
if (count == data.Length)
{
speed = (count * 1.0 / 1024 / spam) * 1000;
}
//进度条
m = m + n;
//控件显示
ShowProbar(o, m, speed);
} while (count > 0);
}
if (this.progressBar1.Value == 100)
{
System.Threading.Thread.Sleep(1000); //延迟1秒弹出
MessageBox.Show("拷贝成功!");
}
});
}
本源码包内暂不包含可直接显示的源代码文件,请下载源码包。