You can use the StreamReader class for reading, and StreamWriter for writing. Unlike the more generalized FileStream class, StreamReader and StreamWriter are specialized classes for text files containing ASCII or Unicode characters . There are useful methods which make text file access more convenient . 18.4.1 Reading using StreamReaderStreamReader has several overloaded constructors but here are the two most useful ones:
If the first constructor is used, StreamReader will try to determine the file's encoding format from the text file itself. [7]
StreamReader supports the following text encoding formats:
For the encoding parameter of your second StreamReader constructor, you can pass in either of the following properties of the System.Text.Encoding class:
StreamReader has two methods useful for reading:
Read() reads in a single character, and returns the int value of the character. ReadLine() reads the whole line until it reaches a newline character and returns the string or null if the end of file has been reached. ReadLine() does not include the newline character in the returned string. Here is an example of how StreamReader can be used to read the loveletter.txt file. 1: using System; 2: using System.IO; 3: 4: public class TestClass{ 5: 6: public static void Main(){ 7: StreamReader sr = new 8: StreamReader("c:\expt\loveletter.txt"); 9: 10: int counter=0; 11: string line = sr.ReadLine(); 12: 13: while (line!=null){ 14: counter++; 15: Console.Write("line #"+counter+" :"); 16: Console.WriteLine(line); 17: line = sr.ReadLine(); 18: } 19: 20: sr.Close(); 21: } 22: } Output: c:\expt>test line #1 :Dear Juliet, line #2 :I yearn for u! line #3 :Your Romeo 18.4.2 Writing using StreamWriterStreamWriter has several overloaded constructors, but here are the two most useful ones:
If the first constructor is used, StreamWriter will use the UTF8 encoding format by default for writing. If the file indicated by path already exists, it is deleted first (not appended to). The second constructor takes in a boolean value to indicate if you want to append your new characters ( true ) or overwrite the entire file if it exists ( false ). You can pass in the same encoding parameter as shown in the previous section. StreamWriter has two methods useful for writing:
The difference between them is that WriteLine appends a newline character automatically to the string. In fact, both methods are overloaded to take in a bool , char , decimal , double , int , long , float , uint , ulong , or char[] instead of a string. Here is a code fragment showing how StreamWriter can be used: 80: StreamWriter sw = new 81: StreamWriter("c:\expt\reply.txt"); 82: 83: sw.WriteLine("Dear Romeo,"); 84: sw.WriteLine("you still owe me cash!"); 85: sw.WriteLine("Your Juliet"); 86: sw.Close(); |