C # text file (. txt) Read and write

Source: Internet
Author: User

 Directory

    • Objective
    • Read TXT file
    • Write TXT file

Preface

The computer initially only supported ASCII encoding, but later in order to support characters in other languages (such as kanji) and some special characters (such as €), the Unicode character set was introduced. There are many encoding methods based on the Unicode character set, such as UTF-7, UTF-8, Unicode, and UTF-32. In the Windows operating system, the first few bytes of a text file are used to specify how the file is encoded

If you use Notepad or WordPad to open a text file, you don't have to worry about how the file is encoded, because these applications read the first few bytes of the file to determine how the file is encoded, and then display each character in the text with the correct encoding. In the following figure, you can see what encoding (Encoding) mode you can choose when you save a document with Notepad Notepad

  You don't have to worry about coding by using. NET to read text files or write to text files. NET has already encapsulated these. When reading a text file, if you already know what encoding the text is using, you can specify which encoding to use to read the text, otherwise if you do not specify the encoding method. NET reads the first few bytes of text to determine which encoding is used to read the contents of the file. You can also specify the encoding you want to use when writing to a text file. If you do not specify the encoding,. NET determines the encoding based on whether the text being written contains special characters. If there are no special characters, ASCII encoding is used, and if there are special characters, the UTF-8 encoding is used.

Read TXT file

If the contents of the file you want to read are not many, you can use File.readalltext (filePath) or specify the encoding method File.readalltext (FilePath, Encoding). They all read the text all at once and return a string containing all the text content

You can also use the method File.ReadAllLines, which reads all the lines of the text content one time, returns an array of strings, and the elements of the array are the contents of each row

When the content of text is larger, we should not read the text content one at a time, but should use stream to read the content.

. NET encapsulates the StreamReader class for us, which is designed to read characters from a byte stream in a particular encoding. The method of the StreamReader class is not a static method, so reading a file using that class first instantiates the class, providing the path to read the file when it is instantiated. There are many ways to instantiate a StreamReader class. Here are some of the things I've listed:

StreamReader sR1 = new StreamReader (@ "C:\temp\a.txt"); You can also specify the encoding method StreamReader sR2 = new StreamReader (@ "C:\temp\a.txt", Encoding.UTF8); FileStream FS = new FileStream (@ "C:\temp\a.txt", FileMode.Open, FileAccess.Read, Fileshare.none); StreamReader sR3 = new StreamReader (FS); StreamReader sR4 = new StreamReader (FS, Encoding.UTF8); FileInfo myFile = new FileInfo (@ "C:\temp\a.txt"); OpenText Create a UTF-8 encoded StreamReader object StreamReader sR5 = Myfile.opentext ();//OpenText Create a UTF-8-encoded StreamReader object Stre Amreader sR6 = File.OpenText (@ "C:\temp\a.txt");

  

After initialization, you can read one line at a time, read a single character at a time, read several characters at a time, and even read all of the contents at once

Reads a line of string nextline = Sr.readline ();
Read a character int nextchar = Sr.read ();
Read 100 characters int n = 100; char[] Chararray = new Char[n]; int ncharsread = Sr.read (chararray, 0, N);
Read all string restofstream = Sr.readtoend ();

After using StreamReader, don't forget to close it: sr.close ();

If we need to read the entire text file in one line, let's look at a complete example:

StreamReader SR = File.OpenText (@ "C:\temp\a.txt"); String nextline; while ((nextline = Sr.readline ()) = null) {     

Write TXT file

  Write the file and read the file, if you want to write not a lot of content, you can use the File.writealltext method to write the content at once as a file. If you want to write the contents of a string to a file, you can use File.writealltext (FilePath) or specify the encoding method File.writealltext (FilePath, Encoding) methods

If you have an array of strings, you write each element of the array as a single line to the file, and you can use the File.writealllines method

String[] STRs = {"Good morning!", "Good afternoon!", "Good evening!"}; File.writealllines (@ "C:\temp\a.txt", STRs); You can also specify the encoding method File.writealllines (@ "C:\temp\a.txt", STRs, Encoding.ascii);

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

When the content to be written is much more, it is also written in the same way as stream

. NET encapsulates the StreamWriter class for us, which writes characters to a byte stream in a specific encoding. The method of the StreamWriter class is also not a static method, so to write to a file using this class first to instantiate the class, instantiate the StreamWriter class also has many ways:

Once initialized, you can write one line at a time with a StreamWriter object, a character, an array of characters, or even part of a character array.

Write a character            SW. Write (' a ');

Again, do not forget to close the StreamWriter object when it is finished. Sw.close (); Finally, consider a complete example of using StreamWriter to write one line at a time:

FileInfo myFile = new FileInfo (@ "C:\temp\a.txt"); StreamWriter SW = Myfile.createtext (); string[] STRs = {"Good Morning", "Nice Afternoon", "Good Evening}";            foreach (var s in STRs) {     sw.writeline (s);} sw.close ();
Article Source: https://www.cnblogs.com/eniac12/p/4398310.html

C # text file (. txt) Read and write

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.