Curriculum
In C#, the TextWriter class is used to write characters to a stream in a sequential manner. It provides methods for writing strings, characters, and formatted text to a stream, as well as methods for flushing the stream and closing the stream.
Here is an example of using TextWriter to write text to a file:
using System.IO; class Program { static void Main() { string filePath = "example.txt"; using (StreamWriter writer = new StreamWriter(filePath)) { writer.WriteLine("Hello, world!"); writer.WriteLine("This is an example of using TextWriter."); writer.Write("The time is now: "); writer.WriteLine(DateTime.Now); } } }
In this example, we create a StreamWriter object by specifying the file path. We then use the WriteLine and Write methods to write text to the file. Finally, we close the StreamWriter object to ensure that all data is flushed to the file.
Here is an example of using TextWriter to write text to the console:
using System; class Program { static void Main() { using (TextWriter writer = Console.Out) { writer.WriteLine("Hello, world!"); writer.WriteLine("This is an example of using TextWriter."); writer.Write("The time is now: "); writer.WriteLine(DateTime.Now); } } }
In this example, we create a TextWriter object that writes to the console by using the Console.Out property. We then use the WriteLine and Write methods to write text to the console.
Overall, TextWriter is a useful class for writing text to streams in C#. It provides a high-level, convenient way to write text, but it does not provide the low-level control and efficiency of FileStream. It also requires careful attention to detail and proper error handling to ensure that streams are written correctly.