C # Reading and Writing text files

Source: Internet
Author: User

In the previous articleArticle. In this article, I will introduce how to use C # To read and write text files.

 

The computer initially only supports ASCII encoding, but later it introduced the Unicode Character Set to support characters (such as Chinese characters) and some special characters (such as €) in other languages. There are many encoding methods based on UNICODE character sets, such as UTF-7, UTF-8, Unicode, and UTF-32. In Windows, the first few bytes of a text file are used to specify the encoding method of the file. If you use notepad or WordPad to open a text file, you do not need to worry about the file encoding method, because these applicationsProgramThe first few bytes of the file are read to determine the encoding method of the file, and then each character in the text is displayed with the correct encoding. In the figure below, we can see which encoding methods can be selected when a document is saved using notepad.

You do not need to worry about encoding when using. Net to read or write text files .. Net has encapsulated these. When reading a text file, if you already know the encoding method used by the text, you can specify the encoding method used to read the text. Otherwise, if you do not specify the encoding method ,. net will read the first few bytes of the text to determine the encoding method used to read the file content. When writing a text file, you can also specify the encoding method you want to use. If no encoding is specified,. Net determines the encoding method based on whether the written text contains special characters. If there are no special characters, it uses ASCII encoding, if there are special characters, it uses UTF-8 encoding.

 

(1) reading files

If you want to read not many files, you can use file. readalltext (filepath) or specify the encoding method file. readalltext (filepath, encoding. They read all the text content at a time and return a string containing all the text content.

StringSTR = file. readalltext (@"C: \ temp \ ascii.txt");//You can also specify the encoding method.StringStr2 = file. readalltext (@"C: \ temp \ ascii.txt", Encoding. ASCII );

You can also use file. readalllines. This method returns a string array. Each row is an array element.

String[] STRs = file. readalllines (@"C: \ temp \ ascii.txt");//You can also specify the encoding method.String[] Strs2 = file. readalllines (@"C: \ temp \ ascii.txt", Encoding. ASCII );

When the text content is large, we should not read the text content once, but use stream to read the content .. Net encapsulates the streamreader class for us. There are many methods to initialize the streamreader class. Below I will list several

Streamreader SR1 = New Streamreader ( @"  Utf-8.txt c: \ temp \  " );  //  You can also specify the encoding method. Streamreader Sr2 = New Streamreader ( @"  Utf-8.txt c: \ temp \  "  , Encoding. utf8); filestream FS = New Filestream ( @"  Utf-8.txt c: \ temp \  "  , Filemode. Open, fileaccess. Read, fileshare. None); streamreader sr3 =New  Streamreader (FS); streamreader sr4 = New  Streamreader (FS, encoding. utf8); fileinfo myfile = New Fileinfo ( @"  Utf-8.txt c: \ temp \  "  );  //  Opentext creates a UTF-8-encoded streamreader object Streamreader sr5 = Myfile. opentext ();  // Opentext creates a UTF-8-encoded streamreader object Streamreader sr6 = file. opentext ( @"  Utf-8.txt c: \ temp \  " );

After initialization, you can read a row or a character each time. You can also read several characters or even read all the content at a time.

 //  Read a row  String Nextline = Sr. Readline ();  //  Read one character  Int Nextchar = Sr. Read ();  // Read 100 characters  Int Nchars = 100  ;  Char [] Chararray = New   Char  [Nchars];  Int Ncharsread = Sr. Read (chararray, 0  , Nchars );  //  Read all  String Restofstream = Sr. readtoend ();

After streamreader is used, do not forget to close it: Sr. closee ();

If we need to read the entire text file in one row, let's take a complete example:

 
Streamreader sr = file. opentext (@"C: \ temp \ ascii.txt");StringNextline;While(Nextline = Sr. Readline ())! =Null) {Console. writeline (nextline);} Sr. Close ();

 

(2) Writing files

Writing a file is the same as reading a file. If you want to write less content, you can use the file. writealltext method to write all the content at a time as a file. If you want to write the content of a string to a file, you can use file. writealltext (filepath) or specify the encoding method file. writealltext (filepath, encoding.

StringStr1 ="Good morning!"; File. writealltext (@"C: \ temp \ test \ ascii.txt", Str1 );//You can also specify the encoding method.File. writealltext (@"C: \ temp \ test \ ascii-2.txt", Str1, encoding. ASCII );

If you have a string array and want to write each string element into the file, you can use the file. writealllines method:

String[] STRs = {"Good morning!","Good afternoon!"}; File. writealllines (@"C: \ temp \ ascii.txt", STRs); file. writealllines (@"Ascii-2.txt c: \ temp \", STRs, encoding. ASCII );

When the file. writealltext or file. writealllines method is used, if the specified file path does not exist, a new file is created. If the file already exists, the original file is overwritten.

 

When you want to write a large amount of content, you also need to use stream writing .. The class encapsulated by. NET is streamwriter. There are also many methods to initialize the streamwriter class:

//  If the file does not exist, create a file. If yes, overwrite the file. Streamwriter SW1 = New Streamwriter ( @"  Utf-8.txt c: \ temp \  "  );  //  You can also specify the encoding method.  //  True is append text, and false is used to overwrite the original file. Streamwriter sw2 = New Streamwriter ( @"  Utf-8.txt c: \ temp \ " , True  , Encoding. utf8 );  //  Filemode. createnew: Creates a file if the file does not exist. If the file already exists, an exception is thrown. Filestream FS = New Filestream ( @"  Utf-8.txt c: \ temp \  "  , Filemode. createnew, fileaccess. Write, fileshare. Read );  //  UTF-8 is default encoding Streamwriter sw3 = New Streamwriter (FS); streamwriter sw4 = New  Streamwriter (FS, encoding. utf8 );  //  If the file does not exist, create a file. If yes, overwrite the file. Fileinfo myfile = New Fileinfo ( @"  Utf-8.txt c: \ temp \  "  ); Streamwriter sw5 = Myfile. createtext ();

After initialization, you can use a streamwriter object to write a row, a character, a character array, or even a part of a character array at a time.

  //   write a character  SW. write ( '  A   '  );   //   write an array of characters   char  [] chararray =  New   char  [ 100  ];  ///   initialize these characters   SW. write (chararray);  ///   write a part of a character array  SW. write (chararray,  10 ,  15 ); 

Similarly, do not close streamwriter objects after they are used up. Sw. Close (); finally, let's take a complete example of using streamwriter to write a row at a time:

 
Fileinfo myfile =NewFileinfo (@"Utf-8.txt c: \ temp \"); Streamwriter SW=Myfile. createtext ();String[] STRs = {"Good morning","Good afternoon"};Foreach(VaRSInSTRs) {Sw. writeline (s);} Sw. Close ();

 

Related Article

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.