.NET API Documentation

Home

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

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

SignatureDescription
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

NameTypeDescription
EncodingEncodingGets the encoding used by the current writer.
AutoFlushboolIndicates whether the writer flushes its buffer after each write operation.
BaseStreamStreamGets the underlying stream.

Methods

NameSignatureDescription
Writevoid Write(string value)Writes a string to the stream.
WriteLinevoid WriteLine(string value)Writes a string followed by a line terminator.
Flushvoid Flush()Clears buffers and writes any buffered data to the underlying device.
Closevoid 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());
        }
    }
}