.NET API Docs

Home

System.IO.StringWriter Class

Provides a TextWriter for writing information to a string. The written string can be retrieved using the ToString() method.

Overview
Properties
Methods
Example

Inheritance

System.Object → System.IO.TextWriter → System.IO.StringWriter

Implements

System.IDisposable, System.IAsyncDisposable

PropertyDescription
EncodingGets the Encoding in which the output is written. Always returns UTF-16 (UnicodeEncoding).
NewLineGets or sets the line terminator string used by the current StringWriter object.
StringBuilderGets the underlying StringBuilder used to store the written characters.
MethodSignatureDescription
Writevoid Write(char value)Writes a single character to the underlying string.
Writevoid Write(string value)Writes a string to the underlying string.
WriteLinevoid WriteLine()Writes the current line terminator to the underlying string.
WriteLinevoid WriteLine(string value)Writes a string followed by the current line terminator.
GetStringBuilderStringBuilder GetStringBuilder()Returns a reference to the underlying StringBuilder.
ToStringoverride string ToString()Returns the accumulated string.

Basic Usage

// Using System.IO and System.Text
using System;
using System.IO;

class Program
{
    static void Main()
    {
        using var writer = new StringWriter();
        writer.WriteLine("Hello, World!");
        writer.WriteLine("Current time: {0}", DateTime.Now);
        writer.NewLine = "\n---\n";

        writer.WriteLine("Section break");

        string result = writer.ToString();
        Console.WriteLine("----- Result -----");
        Console.WriteLine(result);
    }
}

This example demonstrates creating a StringWriter, writing text with line breaks, customizing the NewLine property, and retrieving the final string.