C# StringWriter
last modified April 20, 2025
This tutorial explains how to use the StringWriter class in C# to write and manipulate strings efficiently. StringWriter provides methods for writing text to a StringBuilder.
The StringWriter class writes text to a StringBuilder object. It inherits from TextWriter and provides string-specific functionality.
StringWriter
is useful for building strings from multiple
fragments or when you need TextWriter functionality with strings. It
handles various data types and supports formatting.
Basic StringWriter Example
This example demonstrates basic usage of StringWriter to create a string from multiple writes. We'll build a simple text message.
using System; using System.IO; using System.Text; class Program { static void Main() { using (StringWriter writer = new StringWriter()) { writer.Write("Hello, "); writer.WriteLine("world!"); writer.Write("Current date: "); writer.WriteLine(DateTime.Now.ToString("d")); string result = writer.ToString(); Console.WriteLine(result); } } }
The program creates a StringWriter and writes several text fragments.
Write
and WriteLine
methods work like Console.
The example demonstrates how StringWriter accumulates text in memory.
The ToString
method retrieves the complete string. The using
statement ensures proper disposal. StringWriter uses StringBuilder
internally for efficient string concatenation.
Formatting with StringWriter
StringWriter supports composite formatting like Console and other TextWriter implementations. This example shows formatted output.
using System; using System.IO; class Program { static void Main() { using (StringWriter writer = new StringWriter()) { string name = "John"; int age = 35; double score = 92.5; writer.WriteLine("Name: {0}, Age: {1}", name, age); writer.WriteLine("Score: {0:F2}%", score); writer.WriteLine("Today: {0:D}", DateTime.Now); Console.WriteLine(writer.ToString()); } } }
The example demonstrates various formatting options with StringWriter. Numeric values, dates, and custom formats are all supported. Placeholders {0}, {1} etc. are replaced with formatted values.
Format strings like "F2" (2 decimal places) and "D" (long date) work the same as with Console.WriteLine. StringWriter provides consistent formatting behavior across all TextWriter implementations.
StringWriter with StringBuilder
StringWriter can be initialized with a specific StringBuilder. This example shows how to reuse a StringBuilder with multiple writers.
using System; using System.IO; using System.Text; class Program { static void Main() { StringBuilder sb = new StringBuilder(); using (StringWriter writer1 = new StringWriter(sb)) { writer1.WriteLine("First section:"); writer1.WriteLine("-------------"); writer1.WriteLine("Item 1"); writer1.WriteLine("Item 2"); } using (StringWriter writer2 = new StringWriter(sb)) { writer2.WriteLine(); writer2.WriteLine("Second section:"); writer2.WriteLine("--------------"); writer2.WriteLine("Item A"); writer2.WriteLine("Item B"); } Console.WriteLine(sb.ToString()); } }
The same StringBuilder is used with two different StringWriter instances. Each writer appends content to the shared StringBuilder. This approach allows building complex strings in multiple stages.
The StringBuilder maintains all content between writer usages. This is useful when generating reports or documents with separate sections. StringWriter provides TextWriter interface for StringBuilder operations.
Culture-Specific Formatting
StringWriter can use specific culture settings for formatting. This example demonstrates culture-aware number and date formatting.
using System; using System.Globalization; using System.IO; class Program { static void Main() { var usCulture = new CultureInfo("en-US"); var frCulture = new CultureInfo("fr-FR"); double amount = 1234.56; DateTime date = new DateTime(2023, 12, 31); using (StringWriter writer = new StringWriter()) { writer.WriteLine("US format:"); writer.WriteLine(amount.ToString("C", usCulture)); writer.WriteLine(date.ToString("D", usCulture)); writer.WriteLine(); writer.WriteLine("French format:"); writer.WriteLine(amount.ToString("C", frCulture)); writer.WriteLine(date.ToString("D", frCulture)); Console.WriteLine(writer.ToString()); } } }
The example shows the same numeric and date values formatted for US and French cultures. Currency symbols, decimal separators, and date formats vary by culture.
StringWriter inherits the current culture by default but can format using any specified culture. This is important for internationalized applications that need locale-specific output.
Writing XML with StringWriter
StringWriter is often used with XML writers to generate XML strings. This example creates a simple XML document in memory.
using System; using System.IO; using System.Xml; class Program { static void Main() { using (StringWriter writer = new StringWriter()) using (XmlTextWriter xmlWriter = new XmlTextWriter(writer)) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("Products"); xmlWriter.WriteStartElement("Product"); xmlWriter.WriteAttributeString("ID", "101"); xmlWriter.WriteElementString("Name", "Laptop"); xmlWriter.WriteElementString("Price", "999.99"); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("Product"); xmlWriter.WriteAttributeString("ID", "102"); xmlWriter.WriteElementString("Name", "Mouse"); xmlWriter.WriteElementString("Price", "19.99"); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); Console.WriteLine(writer.ToString()); } } }
The example uses XmlTextWriter with StringWriter to generate formatted XML. All XML output goes to the StringWriter's internal buffer.
StringWriter is ideal for XML generation when you need the result as a string rather than a file. The indented formatting makes the XML human-readable. This approach is common in web services and APIs.
Combining StringWriter with StringReader
This example shows how to use StringWriter with StringReader for string processing. We'll write data then read it back.
using System; using System.IO; class Program { static void Main() { string csvData; // Write CSV data using (StringWriter writer = new StringWriter()) { writer.WriteLine("Name,Age,Occupation"); writer.WriteLine("John Smith,35,Engineer"); writer.WriteLine("Jane Doe,28,Designer"); writer.WriteLine("Bob Johnson,42,Manager"); csvData = writer.ToString(); } // Read CSV data Console.WriteLine("CSV Content:"); using (StringReader reader = new StringReader(csvData)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } }
The program first writes CSV-formatted data to a StringWriter. The resulting string is then read line by line using StringReader.
This demonstrates how StringWriter and StringReader can work together for in-memory string processing. The approach is useful for temporary data formatting and parsing without file I/O overhead.
Custom StringWriter with Overrides
You can create custom StringWriter classes by overriding methods. This example shows a custom writer that transforms output.
using System; using System.IO; using System.Text; class UppercaseStringWriter : StringWriter { public override void Write(char value) { base.Write(char.ToUpper(value)); } public override void Write(string value) { if (value != null) { base.Write(value.ToUpper()); } } public override void WriteLine(string value) { if (value != null) { base.WriteLine(value.ToUpper()); } else { base.WriteLine(); } } } class Program { static void Main() { using (UppercaseStringWriter writer = new UppercaseStringWriter()) { writer.WriteLine("this will be uppercase"); writer.Write("mixed CASE "); writer.Write("text"); writer.WriteLine(); writer.Write('a'); writer.Write('b'); writer.Write('c'); Console.WriteLine(writer.ToString()); } } }
The UppercaseStringWriter class inherits from StringWriter and overrides key methods to transform output to uppercase. All writes pass through the custom transformations.
This technique allows creating specialized string writers for specific needs like case conversion, encoding, or logging. The example shows how to override individual write methods for different data types.
Source
StringWriter Class Documentation
This tutorial covered writing and manipulating strings in C# with StringWriter, including formatting, XML generation, and custom implementations.
Author
List all C# tutorials.