C # manipulating text files

Source: Internet
Author: User

The computer initially only supported ASCII encoding , but later in order to support characters in other languages (such as Chinese characters) and some special characters (such as €), it introduced The Unicode character set . 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. The following figure
, you can see which 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 file.readalltext (FilePath, Encoding) the method. They all read the text all at once and return a string containing all the text content

String str1 = File.readalltext (@ "C:\temp\a.txt");

You can also specify the encoding method
String str2 = File.readalltext (@ "C:\temp\a.txt", encoding.ascii);

String str1 = File.readalltext (@ "C:\temp\a.txt");
You can also specify the encoding method
String str2 = File.readalltext (@ "C:\temp\a.txt", encoding.ascii);


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

string[] strs1 = File.ReadAllLines (@ "C:\temp\a.txt");
You can also specify the encoding method
string[] Strs2 = File.ReadAllLines (@ "C:\temp\a.txt", encoding.ascii);

. 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. Instantiation of
There are many ways to StreamReader classes. 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 creating a UTF-8-encoded StreamReader object
StreamReader sR5 = Myfile.opentext ();
OpenText creating a UTF-8-encoded StreamReader object
StreamReader 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

Read a line
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();

When you're finished 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)
{
Console.WriteLine (nextline);
}
Sr.close ();

Write TXT file

Write the file and read the file, if you want to write not a lot of content, you can use file. WriteAllText method to write the contents all 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) method

String str1 = "Good morning!";
File.writealltext (@ "C:\temp\test\a.txt", str1);
You can also specify the encoding method
File.writealltext (@ "C:\temp\test\a.txt", str1, Encoding.ascii);

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 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 you want to write more content, you also use the stream to write

. 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:

If the file does not exist, create the file, or overwrite the file if it exists
StreamWriter sW1 = new StreamWriter (@ "C:\temp\a.txt");

You can also specify the encoding method, True append is AppendText, false to overwrite the original file
StreamWriter sW2 = new StreamWriter (@ "C:\temp\a.txt", true, Encoding.UTF8);

FileMode.CreateNew: Create file If file does not exist, throw exception if file already exists
FileStream FS = new FileStream (@ "C:\temp\a.txt", FileMode.CreateNew, FileAccess.Write, FileShare.Read);
StreamWriter sW3 = new StreamWriter (FS);
StreamWriter sW4 = new StreamWriter (FS, Encoding.UTF8);

If the file does not exist, create the file, or overwrite the file if it exists
FileInfo myFile = new FileInfo (@ "C:\temp\a.txt");
StreamWriter sW5 = Myfile.createtext ();

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 ');

Write a character array
char[] Chararray = new char[100];
Sw. Write (Chararray);

Write part of a character array (10~15)
Sw. Write (Chararray, 10, 15);


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", "Good Afternoon", "Nice evening}";
foreach (var s in STRs)
{
Sw.writeline (s);
}
Sw.close ();

C # manipulating text files

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.