TextWriter
TextWriter is an abstract class in the System.IO namespace that provides a generic way to write characters to a stream. It defines a set of methods for writing different types of data to a stream, such as text, arrays, and objects.
TextWriter is the base class for a number of more specific writer classes, such as StreamWriter and StringWriter. These classes provide additional functionality for writing data to specific types of streams, such as files or strings.
Here are some of the most commonly used methods of TextWriter:
Write: Writes a string or character to the output stream.
WriteLine: Writes a string or character to the output stream, followed by a line terminator.
WriteAsync: Asynchronously writes a string or character to the output stream.
Flush: Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
Here's an example that demonstrates how to use TextWriter to write text to a file:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.txt";
using (TextWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello, world!");
writer.WriteLine("This is a test file.");
}
}
}
In this example, we create a new StreamWriter object that writes to the file at the specified path. We then use the WriteLine method to write two lines of text to the file. The using statement ensures that the writer is properly disposed of when we're finished with it.
Comments
Post a Comment