CHAPTER 16 THE SYSTEM.IO NAMESPACE 535 static (Adult web hosting)

CHAPTER 16 THE SYSTEM.IO NAMESPACE 535 static void Main(string[] args) { Console.WriteLine(”***** Fun with StreamWriter / StreamReader *****n”); // Get a StreamWriter and write string data. StreamWriter writer = File.CreateText(”reminders.txt”); writer.WriteLine(”Don’t forget Mother’s Day this year…”); writer.WriteLine(”Don’t forget Father’s Day this year…”); writer.WriteLine(”Don’t forget these numbers:”); for(int i = 0; i < 10; i++) writer.Write(i + " "); // Insert a new line. writer.Write(writer.NewLine); // Closing automatically flushes! writer.Close(); Console.WriteLine("Created file and wrote some thoughts..."); } Once you run this program, you can examine the contents of this new file (see Figure 16-8). Figure 16-8. The contents of your *.txt file Reading from a Text File Now you need to understand how to programmatically read data from a file using the corresponding StreamReader type. As you recall, this class derives from TextReader, which offers the functionality described in Table 16-8. Table 16-8. TextReader Core Members Member Meaning in Life Peek() Returns the next available character without actually changing the position of the reader. A value of 1 indicates you are at the end of the stream. Read() Reads data from an input stream. ReadBlock() Reads a maximum of count characters from the current stream and writes the data to a buffer, beginning at index. ReadLine() Reads a line of characters from the current stream and returns the data as a string (a null string indicates EOF). ReadToEnd() Reads all characters from the current position to the end of the stream and returns them as a single string. If you now extend the current MyStreamWriterReader class to use a StreamReader, you can read in the textual data from the reminders.txt file as shown here:
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

Leave a Reply