C# TextWriter

In C#, the TextWriter class is a foundational class that provides a convenient way to write characters to a stream. It is an abstract base class, which means you cannot directly create an instance of it. However, you can use derived classes like StreamWriter or StringWriter to write text to different types of destinations.

Here’s an example of using TextWriter along with StreamWriter to write text to a file:

using System;
using System.IO;

class Program
    static void Main()
        string filePath = "output.txt";

        // Create a new StreamWriter and specify the file path
        using (StreamWriter writer = new StreamWriter(filePath))
            // Write some text to the file
            writer.WriteLine("Hello, World!");
            writer.WriteLine("This is a test.");

        Console.WriteLine("Text has been written to the file.");

In the example above, we create a new StreamWriter by passing the desired file path as an argument to its constructor. We then use the WriteLine method of the StreamWriter to write text to the file. The using statement ensures that the StreamWriter is properly disposed of after we finish using it.

You can also use TextWriter with other derived classes such as StringWriter to write text to a string buffer, or Console.Out to write text to the console.

Note: Remember to include the System.IO namespace at the beginning of your file to access the TextWriter and related classes.