C# Textwriter

In C# programming, the TextWriter class, found in the System.IO namespace, serves as an abstract class. Its purpose is to facilitate writing text or a consecutive set of characters into various destinations such as files, streams, or text-based outputs. Due to its abstract nature, direct instantiation of the TextWriter class is not possible. Instead, developers can leverage its derived classes such as StreamWriter and StringWriter for carrying out text writing tasks.

The placeholder diagram is styled with a linear gradient background, rounded borders, padding, margin, and centered text alignment. Additionally, it includes an icon with a font size of 3rem and text with a font size of 1rem.

In C#, the TextWriter class provides a foundation for composing text in a buffered fashion and enables writing information both synchronously and asynchronously.

Methods of TextWriter in C#

The primary functions of the TextWriter class in C# consist of various versions for outputting characters, strings, and basic data types, alongside managing resources and ensuring thread protection. TextWriter in C# offers a variety of methods, including:

Method Description
Write() It is used to release characters, strings, object representations, or primitive values. There are multiple overloads to support various types, such as char, string, char[], int, double, long, and others.
WriteLine() It is used to write data followed by a line terminator. It is overloaded to support different data types, just like the Write() function.
Flush() It is used to flush all buffers and write the buffered data to the underlying device or stream.
Close() It shuts down the writer and releases the resources.
Dispose() It frees all resources that are commonly used by the TextWriter.
Synchronized(TextWriter) It returns a thread-safe wrapper around a given TextWriter instance.
WriteAsync() and WriteLineAsync() These methods write asynchronous data or a line terminator. Several overloads are available for async operations with strings and characters.

Creating a TextWriter Object in C#

In C#, the TextWriter class serves as a foundational abstract class within the System.IO namespace. Its primary function is to facilitate the writing of a sequential arrangement of characters to a designated text stream, such as a file or memory location. Given its abstract nature, direct instantiation of TextWriter objects is not permitted. Instead, we create instances through its derived classes like StreamWriter, or through the utilization of factory methods like File.CreateText, which grants access to a StreamWriter instance.

Syntax

Example

TextWriter = File.CreateText(filePath);

Or

TextWriter textWriter = new StreamWriter("filePath.txt");

C# TextWriter Example

Let's explore a basic illustration of utilizing the TextWriter class to write a pair of lines of information.

Example

Example

using System;  

using System.IO;  

namespace TextWriterExample  

{  

    class Program  

    {  

        static void Main(string[] args)  

        {  

            using (TextWriter writer = File.CreateText("hello world.txt"))  

            {  

                writer.WriteLine("Hello C#");  

                writer.WriteLine("C# File Handling by C# Tutorial");  

            }  

            Console.WriteLine("Data written successfully...");  

        }  

    }  

}

Output:

Output

Data written successfully...

hello world.txt:

Hello C#

C# File Handling by C# Tutorial

Explanation:

In this instance, we showcase employing TextWriter along with File.CreateText to input information into a file named greetings universe.txt. Initially, it adds a duo of text lines to the file and subsequently automatically terminates it because of the employing statement, guaranteeing correct resource handling. Ultimately, it displays a triumph notification on the console.

Using TextWriter with StreamWriter

TextWriter serves as the foundational abstract class, whereas StreamWriter serves as a tangible implementation utilized for text composition within streams or files in the C# programming language.

  • StreamWriter's Relationship with TextWriter: Within C#, the StreamWriter class is built upon the TextWriter abstract class. Hence, it encompasses all the elements of TextWriter, like Write, WriteLine, Flush, and Close, in addition to extra capabilities for scripting characters to various streams (e.g., files, memory streams).
  • Creation Process: While direct instantiation of TextWriter is impossible, it can be employed as a reference type to allocate an instance of a derived class like StreamWriter. This approach facilitates polymorphism, enabling seamless interaction with diverse TextWriter-derived classes.
  • C# TextWriter Example Using StreamWriter

Let's consider a scenario to demonstrate the utilization of the TextWriter with the StreamWriter class in the C# programming language.

Example

Example

using System;

using System.IO;

class C# Tutorial

{

    static void Main()

    {

        using (TextWriter writer = new StreamWriter("Content.txt"))

        {

            writer.WriteLine("Writing the content using the TextWriter with the help of StreamWriter");

        }

        Console.WriteLine("Data written successfully to File");

    }

}

Output:

Output

Data written successfully to File

Explanation:

In this instance, we showcase the utilization of TextWriter in conjunction with StreamWriter to input text into a file named Content.txt. Subsequently, the using statement guarantees the automatic closure of the file post-writing, and a message indicating success is presented on the console.

Classes Derived from TextWriter in C#

In addition to the StreamWriter, there exist various classes that derive from the TextWriter class and adhere to the functionalities of TextWriter. Below is a compilation of inherited classes that enable the utilization of TextWriter:

Classes Description
IndentedTextWriter It is utilized to insert a tab string and to keep track of the current indentation level.
StreamWriter It is commonly utilized to write characters to a stream using a specific encoding.
StringWriter It is utilized to write data to a string. The data is held in an underlying StringBuilder.
HttpWriter It offers an object of the TextWriter class that is accessible via the intrinsic HttpResponse object.
HtmlTextWriter It is utilized to emit markup characters and text to an ASP.NET server control output stream.

Specifying Text Encoding

In C#, classes like StreamWriter and StreamReader typically employ UTF-8 encoding as the default for text-related tasks such as reading and writing. Nevertheless, there may be situations where an alternative encoding such as ASCII, UTF-16, or UTF-32 is necessary to align with system specifications or to ensure compatibility with external applications.

C# TextWriter Example to Specify Text Encoding

Let's consider a scenario to demonstrate how to define character encoding when using the StreamWriter and StreamReader in C#.

Example

Example

using System;

using System.IO;

using System.Text;

class C# Tutorial

{

    static void Main()

    {

        string path = "EncodedFile.txt";

        string content = "Hello, नमस्";

        using (StreamWriter writer = new StreamWriter(path, false, Encoding.Unicode))

        {

            writer.WriteLine(content);

        }

        Console.WriteLine("Data written successfully with UTF-16 encoding.");

        using (StreamReader reader = new StreamReader(path, Encoding.Unicode))

        {

            string fileContent = reader.ReadToEnd();

            Console.WriteLine("File Content:\n" + fileContent);

        }

    }

}

Output:

Output

Data written successfully with UTF-16 encoding.

File Content:

Hello, नमस्

Explanation:

In this instance, we've selected the text "Hello, नमस्" and saved it to a file named EncodedFile.txt using StreamWriter employing UTF-16 encoding. Subsequently, we retrieved the data utilizing StreamReader with the identical encoding. Following this, the inputted information is securely stored with full Unicode backing. Finally, the application displays both the acknowledgment message and the file's content on the console.

Asynchronous Writing

In C#, the TextWriter provides asynchronous functionalities such as WriteAsync and WriteLineAsync for composing individual characters, arrays, text strings, or formatted content to a stream or file. These functionalities yield a Task object, enabling the utilization of the await keyword to continue program execution post-writing, thereby ensuring the application's responsiveness.

C# Asynchronous Writing Example Using TextWriter

Let's consider a scenario to demonstrate asynchronous writing by employing the TextWriter class in C#.

Example

Example

using System;

using System.IO;

using System.Threading.Tasks;

class C# Tutorial

{

    static void Main()

    {

        RunAsync().GetAwaiter().GetResult();

    }

    static async Task RunAsync()

    {

        string path = "AsyncFile.txt";

        string content = "This is written asynchronously using StreamWriter.";

        using (StreamWriter writer = new StreamWriter(path, false))

        {

            await writer.WriteLineAsync(content);

            await writer.WriteLineAsync("Asynchronous writing allows non-blocking I/O operations.");

        }

        Console.WriteLine("Data written successfully using asynchronous writing.");

    }

}

Output:

Output

Data written successfully using asynchronous writing.

Explanation:

In this instance, we showcase asynchronous writing to files in C# by employing the StreamWriter.WriteLineAsync function. Following this, the Main function triggers RunAsync using GetAwaiter.GetResult to run the asynchronous task in a synchronous context. Inside RunAsync, a StreamWriter asynchronously writes two lines of text using WriteLineAsync, enabling non-blocking input/output operations, and once finished, a confirmation message is displayed on the console.

Writing formatted data

Creating structured data using C# TextWriter allows for specifying the appearance of values through customized layouts, padding, alignment, and specific number or date formats using format strings and placeholders within methods like Write and WriteLine.

C# TextWriter Example to Write Formatted Data

Let's consider a scenario to demonstrate the process of formatting data with the TextWriter class in the C# programming language.

Example

Example

using System;

using System.IO;

class Ex1

{

    static void Main()

    {

        string path = "FormattedData.txt";

        using (TextWriter writer = new StreamWriter(path))

        {

            writer.WriteLine("Name: {0}, Age: {1}, Score: {2}", "Jhonson", 25, 89.5);

            writer.WriteLine("{0,-10} {1,5} {2,8}", "Name", "Age", "Score");

            writer.WriteLine("{0,-10} {1,5} {2,8}", "Maddy", 27, 92.3);

            writer.WriteLine("{0,-10} {1,5} {2,8}", "Peter", 22, 76.8);

            string city = "New York";

            int population = 8500000;

            writer.WriteLine($"City: {city}, Population: {population:N0}");

        }

        Console.WriteLine("Formatted data written successfully.");

    }

}

Output:

Output

Formatted data written successfully.

Explanation:

In this instance, we showcase the utilization of TextWriter in conjunction with StreamWriter for the purpose of inscribing structured information into a file. In this scenario, we employ composite formatting featuring placeholders {0}, {1}, and so forth, tabular presentation with width specifications to ensure proper alignment, and string interpolation to display details such as city and population. Following the data inscription process, a confirmation message indicating the successful operation is displayed on the screen.

Writing to Multiple Writers

In C# programming, we have the ability to generate numerous destinations by developing a personalized class that derives from TextWriter and redefines various methods like Write and WriteLine. Within these redefinitions, we can redirect the content to multiple TextWriter instances.

C# Example for Writing to Multiple Writers using TextWriter

Let's consider an example to demonstrate the process of implementing multiple writers using the TextWriter class in C#.

Example

Example

using System;

using System.IO;

using System.Text;

class MultiWriter : TextWriter

{

    private readonly TextWriter[] writers;

    public MultiWriter(params TextWriter[] writers)

    {

        this.writers = writers;

    }

    public override Encoding Encoding => Encoding.UTF8;

    public override void WriteLine(string val)

    {

        foreach (var writer in writers)

        {

            writer.WriteLine(val);

        }

    }

    public override void Write(char val)

    {

        foreach (var writer in writers)

        {

            writer.Write(val);

        }

    }

}

class New

{

    static void Main()

    {

        using (var fileWriter = new StreamWriter("a.txt"))

        using (var multiWriter = new MultiWriter(Console.Out, fileWriter))

        {

            multiWriter.WriteLine("Writing to both Console and File at the same time.");

            multiWriter.WriteLine("Have a great Day.");

        }

        Console.WriteLine("Data written successfully to console and file.");

    }

}

Output:

Output

Writing to both Console and File at the same time.

Have a great Day.

Data written successfully to console and file.

Explanation:

In this instance, we are examining a specialized MultiWriter class that extends TextWriter and redefines the Write and WriteLine functions to send output to multiple destinations. When Console.Out and a StreamWriter for a file are provided as parameters, the application concurrently logs identical content to both the console and the specified file.

Features of the TextWriter Class in C#

There are several features of the TextWriter class in C#. Some of them are as follows:

  • In C#, this class provides several methods to write data in string, character, and line formats.
  • The TextWriter class provides built-in support for async and await operations.
  • This function can be extended by custom classes for specific writing.
  • It provides buffered writing to enhance performance.
  • This function belongs to the System.IO.namespace.
  • Conclusion

In summary, the abstract class TextWriter in C# provides a versatile method for writing text information to different destinations such as files, streams, or strings. As it is not designed for direct instantiation, it operates through derived classes like StreamWriter and StringWriter. By utilizing the TextWriter class, programmers benefit from a unified interface for text composition, promoting code reusability, cleaner architecture, and automatic resource management when employed with the using statement. This component plays a crucial role in handling text-based output in the C# programming language.

C# TextWriter FAQs

No, it is not possible to directly create an instance of the TextWriter class.

No, as it is an abstract class, we create instances of derived classes such as StreamWriter or StringWriter.

The primary distinction between Write and WriteLine is that Write does not automatically move the cursor to a new line after displaying the text, whereas WriteLine does.

The primary contrast between the Write and WriteLine methods lies in the fact that the Write function outputs data without adding a newline character, while the WriteLine method appends data along with a newline character.

3) What is the use of Flush in TextWriter?

In C#, invoking the flush method empties all buffers, ensuring immediate writing of data to the storage system.

4) Is the TextWriter function thread-safe in C#?

No, as a default setting, it is not designed to be thread-safe. In scenarios where multiple threads are involved, it is essential to synchronize access manually.

5) Is it possible to utilize TextWriter for storing data in memory in C#?

In C#, the TextWriter class is capable of writing data to memory by utilizing the StringWriter class. This functionality enables the creation and modification of text solely within the computer's memory. Such capability proves beneficial for tasks like formatting output, logging information, or generating dynamic content without interacting with the file system.

Input Required

This code uses input(). Please provide values below: