Text File Input and Output with StreamReader and StreamWriter


Text File Input and Output with StreamReader and StreamWriter

The StreamReader and StreamWriter classes are specially designed to represent character streams and contain members that make reading from and writing to text files convenient. These streams can only be used with text files. A few of their methods are shown in Tables 22.3 and 22.4.

Both stream classes contain a method called Close that closes the related stream. This releases the resources allocated to the stream and allows other parts of the program access to the underlying file (usually only one stream can access a file at any one time). Furthermore, a stream that is left unclosed without an associated running program is prone to be damaged.

Even if you don't close a stream explicitly with the Close method, the system automatically closes the file when the program ends in a normal fashion. However, if the program ends abnormally (crashes), the runtime does not get the chance to close the files. Thus, you should always close a stream as soon as possible, after you have finished using it.

Table 22.3. A Few Selected StreamWriter Class Members
StreamWriter class member Description
Close Closes the output stream and releases any associated resources.
Write Writes one or more characters to the stream without inserting a newline character.
WriteLine Writes one or more characters to the stream and inserts a newline character.

Table 22.4. A Few Selected StreamReader Class Members
StreamReader class member Description
Close Closes the input stream and releases any associated resources.
Read Reads the next character (or number of characters) from the input stream.
ReadLine Reads the next line of characters and returns this as a string. Returns null when the end of the file is reached.



To see the remaining class members of StreamWriter and StreamReader, please consult the .NET Framework documentation.

The WriteLine method is convenient for writing a line of text (in the form of a string) to a StreamWriter stream. The WriteLine method automatically inserts a newline character after each string argument it writes to the file. For example, if we use a StreamWriter instance called myStreamWriter to write to a file called myFile and call the WriteLine method three times as in the following lines:

 MyStreamWriter.WriteLine("Three lines"); MyStreamWriter.WriteLine("but all"); MyStreamWriter.WriteLine("in one file"); 

myFile will contain three newline (NL) characters, one after each of the three string arguments, as illustrated in Figure 22.1.

Figure 22.1. Content of myFile.

Correspondingly, the ReadLine method reads to the next newline character in the file and returns the characters in this segment of the file as a string. For example, the first time we call the ReadLine method on an input stream accessing myFile shown in Figure 22.1, it returns the string "Three lines", the second time "but all", and so on. When the end of the file is reached, the ReadLine method returns null.

The StreamWriter's Write method is heavily overloaded. You can use this method to write a single character, a string, an array of characters, and many other data elements to the stream. You can view all seventeen overloaded Write methods in the .NET Framework documentation.

As opposed to the WriteLine method, Write does not automatically insert a newline character after its argument has been inserted in the file.

The StreamReader's Read member represents two overloaded methods. The first version takes one argument and simply reads in the next character from the stream. The second version allows you to specify how many characters you want to read from the stream.

Listing 22.2 illustrates how to use the StreamWriter and StreamReader classes. The program (in lines 6 36) reads in three lines (strings) supplied by the user via the console. Each line is through a StreamWriter output stream written to a file called C:\MyTestFiles.MyStory.txt, which is subsequently closed. The program (in lines 38 67) then opens MyStory.txt and, via a StreamReader input stream, reads and outputs the contents of the file to the console.

Listing 22.2 TextInOut.cs
01: using System; 02: using System.IO; 03: 04: class TextReaderWriter 05: { 06:     public static void WriteTextToFile() 07:     { 08:         string textLine; 09:         StreamWriter outStream = null; 10: 11:         try 12:         { 13:             FileInfo textFile = new FileInfo (@"C:\MyTestFiles\MyStory.txt"); 14: 15:             outStream = textFile.CreateText(); 16: 17:             Console.WriteLine("Writing to text file"); 18:             Console.WriteLine("Please write three lines of text\n"); 19: 20:             for (int i = 0; i < 3; i++) 21:             { 22:                 textLine = Console.ReadLine(); 23:                 outStream.WriteLine(textLine); 24:             } 25:         } 26: 27:         catch (IOException exObj) 28:         { 29:             Console.WriteLine(exObj); 30:         } 31: 32:         finally 33:         { 34:             outStream.Close(); 35:         } 36:     } 37: 38:     public static void ReadTextFromFile() 39:     { 40:         string textLine; 41:         StreamReader inStream = null; 42:  43:         try 44:         { 45:             FileInfo textFile = new FileInfo (@"C:\MyTestFiles\MyStory.txt"); 46: 47:             inStream = textFile.OpenText(); 48:             Console.WriteLine("\nReading from text file:\n"); 49:             textLine = inStream.ReadLine(); 50: 51:             while (textLine != null) 52:             { 53:                 Console.WriteLine(textLine); 54:                 textLine = inStream.ReadLine(); 55:             } 56:         } 57: 58:         catch (IOException exObj) 59:         { 60:             Console.WriteLine(exObj); 61:         } 62: 63:         finally 64:         { 65:             inStream.Close(); 66:         } 67:     } 68: } 69: 70: class Tester 71: { 72:     public static void Main() 73:     { 74:         TextReaderWriter.WriteTextToFile(); 75:         TextReaderWriter.ReadTextFromFile(); 76:     } 77: } Writing to text file Please write three lines of text It was a rainy night.<enter> The thunder was rumbling in the distance.<enter> Suddenly a bat flew across the graveyard.<enter> Reading from text file: It was a rainy night. The thunder was rumbling in the distance. Suddenly a bat flew across the graveyard.  

First a new FileInfo instance called textFile is created in line 13. To FileInfo's constructor, the program passes the name of the new file we want to create (C:\MyTestFiles\MyStory.txt).

In line 15, the program calls FileInfo's CreateText method, which returns a StreamWriter instance that writes to the new file C:\MyTestFiles\MyStory.txt; this StreamWriter reference is assigned to outStream. When we connect a file to a stream, as in line 15, we say the file is being opened. If the file did not exist (as is the case with MyStory.txt) a new file is created; if an old file with the same name already did exist, its contents are erased and substituted by the contents of the new file. So in either case, we start with an empty file.

The for loop in lines 20 24 loops three times. During each loop, textLine is assigned a string entered by the user (line 22) and in the next line passed as an argument to the output stream outStream. At the end of the three loops, MyStory.txt contains the characters of the three strings entered by the user.

It is important to close outStream, so in accordance with Chapter 19, "Exception Handling," we include the call to Close in a finally block (lines 32 35) associated with the catch-try statements. This guarantees that outStream is closed, even if an exception is thrown.

A finally block (lines 32 35 and 63 66) can, in case of an abnormal situation, be invoked at any time during the execution of its associated try block. Consequently, the compiler requires that all variables contained in the finally block and declared outside the try block (outStream in line 34 and inStream in line 65) are initialized prior to entering the try block. To avoid a compiler error, the program initializes outStream and inStream to null in lines 9 and 41, respectively.

The WriteTextToFile method (lines 6 36), is called from the Main method in line 74. So by the time the ReadTextFromFile method is called in line 75, MyStory.txt has been created and we can use it to demonstrate the StreamReader class. Let's have a closer look at ReadTextFromFile.

Line 45 creates an instance of FileInfo called textFile. Again, we pass the filename as an argument to the constructor but, as opposed to line 13, this time the file already exists.

In line 47, FileInfo's OpenText method returns a reference to a StreamReader instance with access to FileInfo's associated file MyStory.txt. This reference is assigned to inStream, which can be used to read from MyStory.txt.

As stated earlier, the ReadLine method reads to the next newline character and returns the encountered characters as a string; conversely, if the end of the file has been reached, it returns null. We utilize this knowledge to construct lines 49 55. Line 49 assigns ReadLine's return value to textLine. The result is checked in the while statement that only loops if textLine is not equal to null; this is only the case if the end of the file has not been reached. Thus, if textLine is not null, its contents are sent to the console in line 53. ReadLine is repeatedly called in line 54 until the end of the file is reached and null is assigned to textLine. This construct ensures that each segment of MyStory.txt surrounded by newline characters is sent to the console in line 53.

You can check the contents of MyStory.txt with Notepad.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net