C # Read and Write TxT files
Reading and Writing TxT files in WPF is a regular operation. This article describes in detail how to read and write TxT files in WPF. First, the TxT file needs to read data row by row and use the data read from each row as an element of an array. Therefore, the List <string> data type needs to be introduced. Check the code: copy the public List Code <string> OpenTxt (TextBox tbx) {List <string> txt = new List <string> (); OpenFileDialog openFile = new OpenFileDialog (); openFile. filter = "text file (*. txt) | *. txt | (*. rtf) | *. rtf "; if (openFile. showDialog () = true) {tbx. text = ""; using (StreamReader sr = new StreamReader (openFile. fileName, Encoding. default) {int lineCount = 0; while (sr. peek ()> 0) {lineCount ++; string temp = sr. ReadLine (); txt. add (temp) ;}}return txt;} copy code 1 using (StreamReader sr = new StreamReader (openFile. fileName, Encoding. default) 2 {3 int lineCount = 0; 4 while (sr. peek ()> 0) 5 {6 lineCount ++; 7 string temp = sr. readLine (); 8 txt. add (temp); 9} 10} copy the code. StreamReader saves the TxT content to the List <string> txt row by row in stream mode. Second, the write operation on the TxT file is to write each element in the array List <string> to the TxT file one by one, and save it as a. TxT file. And read the code: copy the Code 1 SaveFileDialog sf = new SaveFileDialog (); 2 sf. title = "Save text Files"; 3 sf. defaultExt = "txt"; 4 sf. filter = "txt files (*. txt) | *. txt | All files (*. *) | *. * "; 5 sf. filterIndex = 1; 6 sf. restoreDirectory = true; 7 if (bool) sf. showDialog () 8 {9 using (FileStream fs = new FileStream (sf. fileName, FileMode. create) 10 {11 using (StreamWriter sw = new StreamWriter (fs, Encoding. default) 12 {13 for (int I = 0; I <txt. count; I ++) 14 {15 sw. writeLine (txt [I]); 16} 17} 18} 19 20} copy the code here. Compared with reading TxT files, FileStream is used in writing.