TextWriter in C# is an abstract base class for writing text to a character stream.
It provides basic functionality for writing text to various outputs, like files, consoles, strings, and network streams.
Since TextWriter is an abstract class, you cannot directly instantiate it, but you can work with its derived classes like StreamWriter and StringWriter.
In this tutorial, we’ll cover:
1. Basics of TextWriter
TextWriter provides a foundation for outputting text to different streams. It includes methods like Write(), WriteLine(), and Flush(). Derived classes, such as StreamWriter and StringWriter, extend its functionality.
Important Members of TextWriter:
- Write(): Writes text without a newline.
- WriteLine(): Writes text followed by a newline.
- Flush(): Clears the buffer and writes data to the underlying stream.
- Close(): Closes the writer and releases resources.
Example: Basic TextWriter Setup
using System; using System.IO; public class BasicTextWriterExample { public static void Main() { using (TextWriter writer = new StreamWriter("basic_example.txt")) { writer.WriteLine("This is a line of text."); writer.WriteLine("This is another line."); writer.Flush(); // Ensures that data is written to the file Console.WriteLine("Data written to file."); } } }
Explanation:
- TextWriter is used as a base type, and StreamWriter is used to write to a file.
- writer.WriteLine() writes text followed by a newline, and Flush() writes buffered data to the file.
Content in basic_example.txt:
This is a line of text. This is another line.
2. Writing Text to a File with StreamWriter
StreamWriter, a derived class of TextWriter, allows us to write text to a file. It’s ideal for file I/O and supports different encodings.
Example: Writing to a File Using StreamWriter
using System; using System.IO; public class StreamWriterExample { public static void Main() { using (TextWriter writer = new StreamWriter("file_example.txt")) { writer.WriteLine("Hello, this is a sample text file."); writer.Write("This line is written without a newline."); writer.WriteLine(" This part is on the same line as the previous text."); Console.WriteLine("Data written to file."); } } }
Explanation:
- StreamWriter is used to write data to file_example.txt.
- Write() writes text without a newline, while WriteLine() adds a newline after writing.
Content in file_example.txt:
Hello, this is a sample text file. This line is written without a newline. This part is on the same line as the previous text.
3. Writing Text to a String with StringWriter
StringWriter is another derived class of TextWriter that writes text data to a StringBuilder instead of a file. It’s useful for constructing strings or formatting output.
Example: Writing to a String with StringWriter
using System; using System.IO; public class StringWriterExample { public static void Main() { using (StringWriter writer = new StringWriter()) { writer.WriteLine("This is written to a string."); writer.Write("This line is part of the same string."); writer.WriteLine(" And another line in the same string."); string output = writer.ToString(); // Get the string content Console.WriteLine("Data written to string:"); Console.WriteLine(output); } } }
Explanation:
- StringWriter writes data to an in-memory string.
- writer.ToString() returns the content written to the StringWriter.
Output:
Data written to string: This is written to a string. This line is part of the same string. And another line in the same string.
4. Using TextWriter with Different Encodings
You can specify encoding for TextWriter using derived classes like StreamWriter. This is useful for text data that requires non-ASCII characters, like Unicode or UTF-32 encoding.
Example: Writing Text with UTF-32 Encoding
using System; using System.IO; using System.Text; public class TextWriterEncodingExample { public static void Main() { using (TextWriter writer = new StreamWriter("utf32_example.txt", false, Encoding.UTF32)) { writer.WriteLine("This is a UTF-32 encoded file."); writer.WriteLine("Encoding allows for a wide range of characters."); Console.WriteLine("Data written with UTF-32 encoding."); } } }
Explanation:
- Encoding.UTF32 specifies UTF-32 encoding for the StreamWriter.
- The output file utf32_example.txt will store text with UTF-32 encoding.
Content in utf32_example.txt:
This is a UTF-32 encoded file. Encoding allows for a wide range of characters.
5. Practical Example: Logging Data with TextWriter
TextWriter is often used for logging, where each log entry includes a timestamp. Here’s an example of writing logs to a file, appending each new entry.
Example: Logging with Timestamps Using TextWriter
using System; using System.IO; public class Logger { private string logFilePath; public Logger(string logFilePath) { this.logFilePath = logFilePath; } public void LogMessage(string message) { using (TextWriter writer = new StreamWriter(logFilePath, true)) { string logEntry = $"{DateTime.Now}: {message}"; writer.WriteLine(logEntry); Console.WriteLine("Log entry added: " + logEntry); } } } public class LogExample { public static void Main() { Logger logger = new Logger("log.txt"); logger.LogMessage("Application started."); logger.LogMessage("Application running smoothly."); logger.LogMessage("Application terminated."); } }
Explanation:
- Logger class uses TextWriter (via StreamWriter) to write logs with timestamps.
- Each log entry is appended to log.txt.
Sample content in log.txt:
2024-10-29 15:00:00: Application started. 2024-10-29 15:05:30: Application running smoothly. 2024-10-29 15:10:00: Application terminated.
Advanced Example: Writing Structured Data with TextWriter
TextWriter can be used to output structured data, like JSON or XML, by formatting the data into a string or file.
Example: Writing JSON-like Data with TextWriter
using System; using System.IO; public class JsonWriter { public void WriteJson(string filePath) { using (TextWriter writer = new StreamWriter(filePath)) { writer.WriteLine("{"); writer.WriteLine(" \"Name\": \"John Doe\","); writer.WriteLine(" \"Age\": 30,"); writer.WriteLine(" \"City\": \"New York\""); writer.WriteLine("}"); Console.WriteLine("JSON data written to file."); } } } public class JsonExample { public static void Main() { JsonWriter jsonWriter = new JsonWriter(); jsonWriter.WriteJson("data.json"); } }
Explanation:
- The WriteJson method writes JSON-formatted data using TextWriter.
- StreamWriter is used to output JSON data to data.json.
Content in data.json:
{ "Name": "John Doe", "Age": 30, "City": "New York" }
Summary
TextWriter in C# provides a flexible and efficient way to write text data to various outputs.
Here’s a recap of the main points:
- Basic Setup: TextWriter provides base functionality for text output.
- Writing to a File: StreamWriter (derived from TextWriter) is used for writing text files.
- Writing to a String: StringWriter is useful for creating in-memory strings.
- Using Different Encodings: Specify custom encodings, like UTF-32, to handle different character sets.
- Logging: TextWriter can be used to log data with timestamps.
- Structured Data: TextWriter supports formatting structured data, such as JSON or XML.
TextWriter is an essential class for text handling in C#, making it easy to write data efficiently to files, strings, and other outputs.