- FileStream can manipulate any file.
- FileStream can manipulate large files.
- StreamReader and StreamWriter are only for text files, and text files are simpler to manipulate.
1 Private voidButton1_Click (Objectsender, EventArgs e)2 {3 //FileStream can read and write any file, SteamReader, Steamwriter is only suitable for reading and writing text files4 5 using(FileStream fs =NewFileStream ("Test.txt", FileMode.OpenOrCreate, FileAccess.Read))6 {7 byte[] buffer =New byte[1024x768*1024x768];//FileStream is required to read and write in byte array form. 8 stringCT ="";9 while(true)//large files need to be read several times, so they need to be read in a loopTen { One intA = fs. Read (Buffer,0, buffer. Length); A -CT + =Encoding.Unicode.GetString (buffer); - if(A = =0) the { - Break; - } - } +TextBox1.Text =CT; - } + A at } - - Private voidButton2_Click (Objectsender, EventArgs e) - { - - //Copy the file test.pdf to Test1.pdf in using(FileStream fsread =NewFileStream ("test.pdf", FileMode.OpenOrCreate, FileAccess.Read)) - { to using(FileStream Fswriter =NewFileStream ("test1.pdf", FileMode.Create, FileAccess.Write)) + { - byte[] bytes =New byte[1024x768*1024x768]; the while(true) * { $ intA = Fsread. Read (Bytes,0, Bytes. Length);Panax NotoginsengFswriter. Write (Bytes,0, a); - if(a==0) the { + Break ; A } the } + } - } $MessageBox.Show ("Replication succeeded"); $ } - - Private voidButton_sr_click (Objectsender, EventArgs e) the { - stringReaders ="";Wuyi using(StreamReader sr =NewStreamReader ("Test.txt", Encoding.default)) the { - Char[] buffer=New Char[ the* the];//prepare a char array as a container Wu while(true)//when the text is too many, not read at once, read all the time - { About intA = Sr. Read (Buffer,0, buffer. Length); $ if(a==0) -{ Break ;} -Readers + =New string(buffer);//re-converting a char array to text - } A + } theTextBox1.Text =readers; - } $ the Private voidButton_sw_click (Objectsender, EventArgs e) the { the using(StreamReader sr=NewStreamReader ("Test.txt", Encoding. Default)) the { - using(StreamWriter sw=NewStreamWriter ("Test2.txt",false, Encoding. Default)) in { the the while(Sr.) Peek () >=0)//use some method to determine whether the end of the file is read, but it seems to lose empty text. About { the stringA=Sr. ReadLine (); the the SW. WriteLine (a); + } - the }Bayi the } the}
The use and difference of FileStream, StreamReader and StreamWriter