17.3.1 read and write in text mode
The SteamReader and StreamWriter classes provide a way for us to read and write data in text mode. The following example reads the content from a text file and prints it on the screen.
Program Listing 17-5:
Using System;
Using System.IO;
Class Filetest
{public
static void Main ()
{
StreamReader srd;
try{
srd=file.opentext ("C:\\c#\\file1\\file1.txt");
}
Catch
{
Console.WriteLine ("File Open Failed");
return;
}
while (SRD. Peek ()!=-1)
{
String str=srd. ReadLine ();
Console.WriteLine (str);
Console.WriteLine ("The end of the file has been reached");
Srd. Close ();
}
}
The method used above OpenText is a static method of the file class and cannot be invoked by an instance of a specific file class. It represents reading a text stream from an existing text file and saving it in a StreamReader instance. The following example writes a text stream to a text file.
Program Listing 17-6:
Using System;
Using System.IO;
Class Filetest
{public
static void Main ()
{
StreamWriter SRD;
try{
srd=file.createtext ("C:\\c#\\file1\\file2.txt");
}
Catch
{
Console.WriteLine ("File create Failed");
return;
}
Srd. WriteLine ("Web address:");
Srd. WriteLine ("www.bianceng.cn");
Srd. WriteLine ("Www.263.net");
Srd.writeline ("Www.microsoft.com/china");
Srd. WriteLine ("www.sina.com.cn");
Srd. Close ();
}
}