Note: Chinese characters are encoded in gb2312 format.
 
Test Page code:
 
Using system;
Using system. Collections. Generic;
Using system. text;
 
Namespace streamreaderandstreamwriter
{
Class Program
{
Static void main (string [] ARGs)
{
Console. writeline ("reading text file content ");
Console. Write ("directory of the input text file :");
String sbasefile = console. Readline ();
Streamreaderandstreamwriter. readfile (sbasefile );
Console. writeline ("APPEND file ");
Streamreaderandstreamwriter. appendtext (sbasefile );
}
}
}
Class Page code:
 
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. IO;
 
Namespace streamreaderandstreamwriter
{
Class streamreaderandstreamwriter
{
// Read text files
Public static void readfile (string sfile)
{
If (file. exists (sfile ))
{
// Obtain a file stream object for reading and writing files
Filestream FS = file. openread (sfile );
// Obtain a stream reader pointing to a file stream
Streamreader sr = new streamreader (FS, encoding. getencoding ("gb2312"); // read Chinese characters in the text file in gb2312 encoding. Otherwise, garbled characters are displayed in the read content.
// Read all text content
String data = Sr. readtoend ();
// Close the object and release the resource
Sr. Close ();
FS. Close ();
Console. writeline (string. Format ("reading files >>{ 0}", sfile ));
Console. writeline (data );
}
Else
Console. writeline (string. Format ("{0} does not exist", sfile ));
}
// Append a text file
Public static void appendtext (string sfile)
{
If (file. exists (sfile ))
{
// Edit a text file
Console. writeline ("Enter written content ");
String swrite = console. Readline ();
// Obtain a stream editor pointing to a file stream
Streamwriter Sw = new streamwriter (sfile, true, encoding. getencoding ("gb2312"); // It is very important to check whether the streamwriter () format is clear. sfile declares the Text object; true declares that appedn can be performed; encoding. getencoding ("gb2312") declares a gb2312 encoding to write content to a text file, so as to avoid garbled characters.
Sw. Write (swrite );
// Close the object and release the resource
Sw. Close ();
// Fs. Close ();
Console. writeline ("appending files to {0}", sfile );
}
Else
Console. writeline ("{0} does not exist", sfile );
}
}
}