C# StringReader
last modified November 6, 2026
In this article we show how to use the StringReader class in C#.
StringReader from the System.IO namespace is a
TextReader that reads from a string. It has the same methods as
StreamReader: ReadLine, Read,
Peek, ReadBlock, and ReadToEnd. No
decoding or buffering is involved; the reader just keeps a position in the
string.
It is used to process multi-line strings line by line, to write small
parsers, and to pass in-memory text to code that expects a
TextReader.
Reading lines
The first example parses a configuration text line by line.
var config = """
# server settings
host = localhost
port = 8080
debug = true
""";
using var reader = new StringReader(config);
var settings = new Dictionary<string, string>();
string? line;
while ((line = reader.ReadLine()) is not null)
{
line = line.Trim();
if (line.Length == 0 || line.StartsWith('#'))
{
continue;
}
var parts = line.Split('=', 2, StringSplitOptions.TrimEntries);
settings[parts[0]] = parts[1];
}
foreach (var (key, value) in settings)
{
Console.WriteLine($"{key}: {value}");
}
The raw string literal holds a small configuration with a comment and an empty line.
while ((line = reader.ReadLine()) is not null)
ReadLine returns the next line without its terminator, or
null when the string is exhausted.
var parts = line.Split('=', 2, StringSplitOptions.TrimEntries);
We skip comments and empty lines and split the rest at the first equals sign.
TrimEntries removes the spaces around the key and the value.
$ dotnet run host: localhost port: 8080 debug: true
StringReader, Split, and EnumerateLines
There are several ways to split a string into lines. They differ in how they
handle \r\n and a trailing newline.
var text = "one\ntwo\r\nthree\n";
string[] split = text.Split('\n');
Console.WriteLine($"Split: {split.Length} items: {Show(split)}");
var lines = new List<string>();
using (var reader = new StringReader(text))
{
string? line;
while ((line = reader.ReadLine()) is not null)
{
lines.Add(line);
}
}
Console.WriteLine($"StringReader: {lines.Count} items: {Show(lines)}");
var spanLines = new List<string>();
foreach (var line in text.AsSpan().EnumerateLines())
{
spanLines.Add(line.ToString());
}
Console.WriteLine($"EnumerateLines: {spanLines.Count} items: {Show(spanLines)}");
static string Show(IEnumerable<string> items) =>
string.Join(" ", items.Select(e => $"[{e.Replace("\r", "\\r")}]"));
The text has one Windows line ending and ends with a newline.
string[] split = text.Split('\n');
Splitting at \n leaves the \r at the end of the
second line and produces an empty fourth item after the final newline.
ReadLine handles all line endings and treats the final newline
as the end of the last line, so we get three lines.
foreach (var line in text.AsSpan().EnumerateLines())
EnumerateLines on a span does not allocate a string per line and
also handles \r\n. Unlike ReadLine, it returns an
empty last line after a trailing newline.
$ dotnet run Split: 4 items: [one] [two\r] [three] [] StringReader: 3 items: [one] [two] [three] EnumerateLines: 4 items: [one] [two] [three] []
Parsing with Peek and Read
Read returns the next character and Peek shows it
without moving forward. Both return -1 at the end. This one-character lookahead
is enough to parse a CSV row with quoted fields.
var row = "1,\"Smith, John\",\"say \"\"hi\"\"\",42";
foreach (var field in ParseRow(row))
{
Console.WriteLine($"<{field}>");
}
static List<string> ParseRow(string row)
{
using var reader = new StringReader(row);
var fields = new List<string>();
var current = new System.Text.StringBuilder();
bool quoted = false;
while (reader.Peek() != -1)
{
char c = (char) reader.Read();
if (quoted)
{
if (c == '"' && reader.Peek() == '"')
{
current.Append('"');
reader.Read();
}
else if (c == '"')
{
quoted = false;
}
else
{
current.Append(c);
}
}
else if (c == '"')
{
quoted = true;
}
else if (c == ',')
{
fields.Add(current.ToString());
current.Clear();
}
else
{
current.Append(c);
}
}
fields.Add(current.ToString());
return fields;
}
The row contains a field with a comma inside quotes and a field with escaped quotes. CSV escapes a quote inside a quoted field by doubling it.
if (c == '"' && reader.Peek() == '"')
{
current.Append('"');
reader.Read();
}
Inside a quoted field, a quote followed by another quote is an escaped quote: we append one and consume the second. A quote followed by anything else ends the quoted part.
else if (c == ',')
A comma outside quotes ends the field.
$ dotnet run <1> <Smith, John> <say "hi"> <42>
Fixed-width fields
ReadBlock reads exactly the requested number of characters,
unless the end of the text comes first. It suits fixed-width record formats.
var data = "HDR1" + "00042" + "Bratislava " + "EUR";
using var reader = new StringReader(data);
string type = ReadField(reader, 4);
int id = int.Parse(ReadField(reader, 5));
string city = ReadField(reader, 20).TrimEnd();
string currency = ReadField(reader, 3);
Console.WriteLine($"type={type} id={id} city={city} currency={currency}");
Console.WriteLine($"Rest: '{reader.ReadToEnd()}'");
static string ReadField(TextReader reader, int width)
{
Span<char> buffer = stackalloc char[width];
int n = reader.ReadBlock(buffer);
if (n < width)
{
throw new FormatException($"expected {width} characters, got {n}");
}
return buffer.ToString();
}
The record has a 4-character type, a 5-digit id, a 20-character city padded with spaces, and a 3-letter currency code.
int n = reader.ReadBlock(buffer);
The method returns the number of characters read. A smaller number means the record was too short, which we report as a format error.
ReadField takes a TextReader, so it works with any
reader, not just a StringReader.
$ dotnet run type=HDR1 id=42 city=Bratislava currency=EUR Rest: ''
Reading the rest
ReadToEnd returns everything from the current position.
Combined with ReadLine, it splits a message into headers and a
body.
var message = """
Subject: Meeting
From: anna@example.com
The meeting is moved to Friday.
Please bring the report.
""";
using var reader = new StringReader(message);
string? line;
while ((line = reader.ReadLine()) is not null && line.Length > 0)
{
Console.WriteLine($"Header: {line}");
}
string body = reader.ReadToEnd();
Console.WriteLine($"Body ({body.Length} chars):");
Console.WriteLine(body);
Console.WriteLine($"After ReadToEnd: Peek = {reader.Peek()}, ReadLine is null: {reader.ReadLine() is null}");
An empty line separates the headers from the body, as in email and HTTP messages.
while ((line = reader.ReadLine()) is not null && line.Length > 0)
We read headers until the first empty line. That line is consumed, so the position is at the first character of the body.
string body = reader.ReadToEnd();
The body is the rest of the string. After that, Peek returns -1
and ReadLine returns null.
$ dotnet run Header: Subject: Meeting Header: From: anna@example.com Body (56 chars): The meeting is moved to Friday. Please bring the report. After ReadToEnd: Peek = -1, ReadLine is null: True
Edge cases
This example shows how many lines ReadLine returns for short
strings and what happens with invalid use.
Count("");
Count("\n");
Count("a");
Count("a\n");
Count("a\n\nb");
try
{
var reader = new StringReader(null!);
}
catch (ArgumentNullException e)
{
Console.WriteLine($"{e.GetType().Name}: {e.ParamName}");
}
var r = new StringReader("abc");
r.Dispose();
try
{
r.Read();
}
catch (ObjectDisposedException e)
{
Console.WriteLine(e.GetType().Name);
}
static void Count(string s)
{
using var reader = new StringReader(s);
int n = 0;
while (reader.ReadLine() is not null)
{
n++;
}
Console.WriteLine($"{"\"" + s.Replace("\n", "\\n") + "\"",-9} -> {n} lines");
}
An empty string has no lines. A string with only a newline has one empty line. A trailing newline does not add a line, but an empty line in the middle counts.
var reader = new StringReader(null!);
The constructor rejects null with an
ArgumentNullException.
r.Read();
A disposed reader throws an ObjectDisposedException.
$ dotnet run "" -> 0 lines "\n" -> 1 lines "a" -> 1 lines "a\n" -> 1 lines "a\n\nb" -> 3 lines ArgumentNullException: s ObjectDisposedException
Testing code that reads a TextReader
When a method takes a TextReader instead of a file name, a
StringReader can feed it test data without creating files.
var input = new StringReader("""
apple 3
pear 2
apple 4
plum 1
""");
foreach (var (fruit, total) in Totals(input))
{
Console.WriteLine($"{fruit}: {total}");
}
File.WriteAllText("orders.txt", "pear 10\nplum 5\npear 1\n");
using (var file = new StreamReader("orders.txt"))
{
Console.WriteLine(string.Join(", ", Totals(file)));
}
File.Delete("orders.txt");
static SortedDictionary<string, int> Totals(TextReader reader)
{
var totals = new SortedDictionary<string, int>();
string? line;
while ((line = reader.ReadLine()) is not null)
{
var parts = line.Split(' ');
totals[parts[0]] = totals.GetValueOrDefault(parts[0]) + int.Parse(parts[1]);
}
return totals;
}
Totals sums quantities per fruit from lines of the form
name quantity.
static SortedDictionary<string, int> Totals(TextReader reader)
The method does not know where the text comes from. We call it once with a
StringReader and once with a StreamReader over a
file.
$ dotnet run apple: 7 pear: 2 plum: 1 [pear, 11], [plum, 5]
Source
In this article we have used StringReader to read strings line by
line, parse characters with lookahead, read fixed-width fields, and feed
in-memory text to TextReader-based code.
Author
List all C# tutorials.