C# StreamWriter Class: Complete Guide
The StreamWriter class in C# is used to write data to a stream. It is a derived class of the TextWriter class and can write characters, strings, and other data types to a stream. The StreamWriter class provides convenient methods for writing different types of data.
The constructor of the StreamWriter class can accept various parameters for specifying the stream to write to and the encoding. If a stream is not specified, a new FileStream object will be created to write to a file. The Using statement can be used to ensure that the stream is closed after use.
Here are some common methods of the StreamWriter class:
- Write method: used to write a character or a string to the stream.
StreamWriter writer = new StreamWriter("file.txt");
writer.Write('A');
writer.WriteLine("Hello");
- WriteLine method: Writes a string and a newline character to the stream.
StreamWriter writer = new StreamWriter("file.txt");
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
- WriteAsync and WriteLineAsync methods: asynchronously write data to a stream.
StreamWriter writer = new StreamWriter("file.txt");
await writer.WriteAsync("Hello");
await writer.WriteLineAsync("World");
- Flush method: writes the data in the buffer to the stream immediately.
StreamWriter writer = new StreamWriter("file.txt");
writer.Write("Hello");
writer.Flush();
- Close and Dispose methods: Close the stream and release associated resources.
StreamWriter writer = new StreamWriter("file.txt");
writer.Write("Hello");
writer.Close();
The StreamWriter class also offers additional methods and properties to control the behavior of the write stream. Using these methods, it is convenient to write data to the stream and manage the stream.