C # Read and Write TxT files

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.