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
Property | Description |
---|---|
Encoding | Gets the Encoding in which the output is written. Always returns UTF-16 (UnicodeEncoding ). |
NewLine | Gets or sets the line terminator string used by the current StringWriter object. |
StringBuilder | Gets the underlying StringBuilder used to store the written characters. |
Method | Signature | Description |
---|---|---|
Write | void Write(char value) | Writes a single character to the underlying string. |
Write | void Write(string value) | Writes a string to the underlying string. |
WriteLine | void WriteLine() | Writes the current line terminator to the underlying string. |
WriteLine | void WriteLine(string value) | Writes a string followed by the current line terminator. |
GetStringBuilder | StringBuilder GetStringBuilder() | Returns a reference to the underlying StringBuilder . |
ToString | override 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.