TextWriter Class in C# with Examples

What is TextWriter Class in C#?

In C#, the TextWriter class represents a writer who can write a sequence of characters. This TextWriter class can be used to write text to a file. It is an abstract base class for StreamWriter and StringWriter, which both write characters to streams and strings. It is used to save text or a sequence of characters in files. It’s in the System.IO namespace. If you look at the definition of TextWriter Class, you’ll notice that it’s an abstract class, as shown in the image below.

Methods of TextWriter class in C#:

  1. Synchronized(TextWriter): It is used to wrap a thread-safe TextWriter in a thread-safe wrapper.
  2. Close() : It terminates the current writer and frees any system resources associated with it.
  3. Dispose() : It frees all of the System.IO.TextWriter object’s resources.
  4. Flush() : It flushes all buffers for the current writer and writes any buffered data to the underlying device.
  5. Write(Char) :It is used to write a character to the text stream.
  6. Write(String) :Its purpose is to write the string to the text stream.
  7. WriteAsync(Char) :It is used to asynchronously write the character to the text stream.
  8. WriteLine() :It is used to write a line ending to the text stream.
  9. WriteLineAsync(String) : It is used to asynchronously write the string to the text stream, followed by a line terminator.

Points to Remember:

  1. The System.IO namespace contains the abstract class TextWriter.
  2. It is used to write a string of characters into a file in a specific order
  3. It is the parent class of the StreamWriter and StringWriter classes, which are used to write characters to streams and strings, respectively.
  4. It is not thread-safe by default.
  5. Its object cannot be created because it is an abstract class. To create a useful instance of TextWriter, any class implementing it must at the very least implement its Write(Char) method.

How TextWriter work in C#?

To use TextWriter in C#, we must first import the System.IO namespace. Because TextWriter is an abstract class, we cannot directly create an instance of it with the new keyword. So, to create the instance, we must use the File class’s CreateText() method as follows:

TextWriter textWriter = File.CreateText(filePath);

The File.CreateText method takes the path of the file to be opened for writing.It creates or opens a file in which UTF-8 encoded text is written. If the file already exists, the content of that file will be overwritten. The File.CreateText(filePath) method returns an instance of the StreamWriter class, which is one of the TextWriter abstract class’s derived classes. We can now use this instance to call the TextWriter class’s methods to write text to a file.

Other classes, such as StreamWriter, are derived from the TextWriter class and provide implementation for TextWriter members. The following is a list of derived classes that can be used to interact with TextWriter:

  1. IndentedTextWriter : It is used to insert a tab string and to keep track of the current level of indentation.
  2. StreamWriter : It is used to write characters in a specific encoding to a stream.
  3. StringWriter : It is used to write data to a string. The data is saved in an underlying StringBuilder.
  4. HttpWriter : It returns a TextWriter object that can be accessed via the intrinsic HttpResponse object.
  5. HtmlTextWriter : It is used to write markup characters and text to the output stream of an ASP.NET server control.

Let’s understand the TextWriter Class with the help of example:

using System; 
using System.IO; 
namespace TextWriter 
{
 public class Program
    {
        public static void Main(string[] args)
        {
            string filePath = @"C:\Users\pc3\Desktop\Excel To DataTable\Files\MyFile.txt";
            using (TextWriter textWriter = File.CreateText(filePath))
            {
                textWriter.WriteLine("Hello TextWriter Abstract Class!");
                textWriter.WriteLine("This is Niki, Testing the TextWriterClass");
            }
            Console.WriteLine("Write Successful");
            Console.ReadKey();
        }

    }
}

Run the code and you can check that the MyFile.txt file is created in the D drive and contains the following information.

We can also write characters to the stream asynchronously by using the WriteAsync(Char) method, as shown in the example below.

using System;
using System.IO;
namespace TextWriter
{
    public class Program
    {
        public static void Main(string[] args)
        {
            WriteCharAsync();
            Console.ReadKey();
        }
        public static async void WriteCharAsync()
        {
            string filePath = @"C:\Users\pc3\Desktop\Excel To DataTable\Files\MyFile1.txt";
            using (TextWriter textWriter = File.CreateText(filePath))
            {
                await textWriter.WriteLineAsync("Hello TextWriter Abstract Class!");
                await textWriter.WriteLineAsync("This is Niki, Testing the TextWriterClass");
            }
            Console.WriteLine("Async Write Successful");
        }
    }
}

Note : In C#, the TextWriter class is used to write text or a sequence of characters to a file. A class derived from the TextWriter class must provide implementation to the TextWriter class’s members.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories