System.IO.StreamWriter Class
Provides a convenient way to write text to a Stream in a particular encoding. The StreamWriter class implements TextWriter and adds methods for writing strings and characters to a stream.
When to use
- Writing text files with specific encodings.
- Appending to existing files.
- Logging data to streams (e.g., network, memory).
Syntax
public sealed class StreamWriter : TextWriter
{
// Constructors
public StreamWriter(Stream stream);
public StreamWriter(string path);
public StreamWriter(string path, bool append);
public StreamWriter(string path, bool append, Encoding encoding);
public StreamWriter(string path, bool append, Encoding encoding, int bufferSize);
// Properties
public Encoding Encoding { get; }
public bool AutoFlush { get; set; }
public Stream BaseStream { get; }
// Methods
public override void Write(string value);
public override void WriteLine(string value);
public void Flush();
public void Close();
}
Constructors
| Signature | Description |
|---|---|
StreamWriter(Stream stream) | Initializes a new instance for the specified stream using UTF-8 encoding. |
StreamWriter(string path) | Creates a new file at the specified path. |
StreamWriter(string path, bool append) | Creates a new file or appends to an existing file. |
StreamWriter(string path, bool append, Encoding encoding) | Specifies encoding and append mode. |
StreamWriter(string path, bool append, Encoding encoding, int bufferSize) | Specifies encoding, append mode, and buffer size. |
Properties
| Name | Type | Description |
|---|---|---|
Encoding | Encoding | Gets the encoding used by the current writer. |
AutoFlush | bool | Indicates whether the writer flushes its buffer after each write operation. |
BaseStream | Stream | Gets the underlying stream. |
Methods
| Name | Signature | Description |
|---|---|---|
Write | void Write(string value) | Writes a string to the stream. |
WriteLine | void WriteLine(string value) | Writes a string followed by a line terminator. |
Flush | void Flush() | Clears buffers and writes any buffered data to the underlying device. |
Close | void Close() | Closes the current writer and the underlying stream. |
Example
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string path = "sample.txt";
// Write text to a file using UTF-8 encoding
using (var writer = new StreamWriter(path, false, Encoding.UTF8))
{
writer.AutoFlush = true;
writer.WriteLine("Hello, World!");
writer.WriteLine($"Current Time: {DateTime.Now}");
}
// Read and display the file contents
Console.WriteLine("File Contents:");
using (var reader = new StreamReader(path, Encoding.UTF8))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}