标签:style blog ar color 使用 sp on 文件 div
1 private void button1_Click(object sender, EventArgs e) 2 { 3 //FileStream可以读写任何文件,SteamReader、SteamWriter只适合读写文本文件 4 5 using (FileStream fs = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read)) 6 { 7 byte[] buffer = new byte[1024 * 1024];//Filestream读取、写入时需要以字节数组形式。 8 string ct = ""; 9 while (true)//大的文件需要分几次读取,所以需要循环读取 10 { 11 int a = fs.Read(buffer, 0, buffer.Length); 12 13 ct += Encoding.Unicode.GetString(buffer); 14 if (a == 0) 15 { 16 break; 17 } 18 } 19 textBox1.Text = ct; 20 } 21 22 23 } 24 25 private void button2_Click(object sender, EventArgs e) 26 { 27 28 //把文件test.pdf复制为test1.pdf 29 using (FileStream fsread = new FileStream("test.pdf", FileMode.OpenOrCreate, FileAccess.Read)) 30 { 31 using (FileStream fswriter = new FileStream("test1.pdf", FileMode.Create, FileAccess.Write)) 32 { 33 byte[] bytes = new byte[1024 * 1024]; 34 while (true) 35 { 36 int a = fsread.Read(bytes, 0, bytes.Length); 37 fswriter.Write(bytes, 0, a); 38 if(a==0) 39 { 40 break ; 41 } 42 } 43 } 44 } 45 MessageBox.Show("复制成功"); 46 } 47 48 private void button_sr_Click(object sender, EventArgs e) 49 { 50 string readers = ""; 51 using (StreamReader sr = new StreamReader("test.txt", Encoding.Default)) 52 { 53 char [] buffer=new char [2014*2014];//准备一个char数组作为容器 54 while (true )//当文本太多,一次没有读完,一直读取 55 { 56 int a = sr.Read(buffer, 0, buffer.Length); 57 if(a==0) 58 {break ;} 59 readers += new string(buffer);//重新把char数组转换成文本 60 } 61 62 } 63 textBox1.Text = readers; 64 } 65 66 private void button_sw_Click(object sender, EventArgs e) 67 { 68 using (StreamReader sr=new StreamReader ("test.txt",Encoding .Default) ) 69 { 70 using (StreamWriter sw=new StreamWriter ("test2.txt",false ,Encoding .Default)) 71 { 72 73 while (sr.Peek ()>=0)//用些方法判断是否读到了文件尾,不过好像会丢失空文本。 74 { 75 string a= sr.ReadLine(); 76 77 sw.WriteLine(a); 78 } 79 80 } 81 82 } 83 }
FileStream、StreamReader、StreamWriter的使用及区别
标签:style blog ar color 使用 sp on 文件 div
原文地址:http://www.cnblogs.com/mytianao/p/4154111.html