文件读写和进度条

View Code
 1         private void Form1_Load(object sender, EventArgs e)
2 {
3 new Thread(copyFileAndProgressBar).Start();
4 progressBar1.Value = 0;
5 timer1.Interval = 2000;
6 timer1.Start();
7 }
8
9 private void timer1_Tick(object sender, EventArgs e)
10 {
11 if (endTime - startTime > 0)
12 progressBar1.Maximum = (int)(endTime - startTime);
13 if (progressBar1.Value == progressBar1.Maximum)
14 {
15 progressBar1.PerformStep();
16 timer1.Enabled = false;
17 timer1.Dispose();
18 return;
19 }
20 progressBar1.Value += 1;
21 }
22
23 //定义开始时间
24 long startTime;
25 //定义结束时间
26 long endTime;
27 //拷贝文件和进度条显示
28 private void copyFileAndProgressBar()
29 {
30 startTime = DateTime.Now.Second;
31 FileStream fsRead = null;
32 BinaryReader br = null;
33 FileStream fsWrite = null;
34 BinaryWriter bw = null;
35 try
36 {
37 fsRead = new FileStream(@"C:\Users\Administrator\Desktop\Office2007.iso",
38 FileMode.Open, FileAccess.Read);
39 int totleSize = (int)fsRead.Length;
40 byte[] buffer;
41 br = new BinaryReader(fsRead);
42 //读取文件
43 buffer = br.ReadBytes(totleSize);
44 //如果存在目标文件,则删除
45 if (File.Exists(@"D:\bak.iso"))
46 File.Delete(@"D:\bak.iso");
47 fsWrite = new FileStream(@"D:\bak.iso", FileMode.Create, FileAccess.Write);
48 bw = new BinaryWriter(fsWrite);
49 //写入二进制流到指定文件
50 bw.Write(buffer);
51 endTime = DateTime.Now.Second;
52 }
53 catch (Exception ex)
54 {
55 throw new Exception(ex.Message);
56 }
57 finally
58 {
59 br.Close();
60 fsRead.Close();
61 bw.Close();
62 fsWrite.Close();
63 }
64 }



 

posted @ 2012-03-25 01:29  ghypnus  阅读(335)  评论(0编辑  收藏  举报