File.ReadAllText is a shortcut. Beneath it, .NET has a general idea: a stream is a sequence of bytes that you can read or write, whether the bytes come from a file, a network connection or memory. Because they all share the Stream base class, code written for one works with the others.
Text is bytes in an encoding
Files hold bytes. Text only exists once an encoding says how bytes map to characters. UTF-8, the default for files in .NET, uses one byte for basic Latin characters and more for others, which is why a string's Length isn't always its size on disk.
using System.Text;
foreach (string text in new[] { "abc", "café", "日本" })
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
Console.WriteLine($"{text}: {text.Length} chars, {bytes.Length} bytes");
}
byte[] data = Encoding.UTF8.GetBytes("é");
Console.WriteLine(Convert.ToHexString(data));
Console.WriteLine(Encoding.UTF8.GetString(data));Check your prediction
abc: 3 chars, 3 bytes
café: 4 chars, 5 bytes
日本: 2 chars, 6 bytes
C3A9
éMemoryStream: a stream without a file
MemoryStream keeps its bytes in memory, which makes it great for trying things and for tests. A stream has a position. After writing, you're at the end, so you must rewind before reading back. Forgetting this is a very common bug.
using var stream = new MemoryStream();
stream.Write(new byte[] { 10, 20, 30 });
Console.WriteLine(stream.Position);
Console.WriteLine(stream.ReadByte());
stream.Position = 0;
Console.WriteLine(stream.ReadByte());
Console.WriteLine(stream.ReadByte());
Console.WriteLine(stream.Length);Check your prediction
3
-1
10
20
3ReadByte returns -1 at the end of a stream, which is the "nothing more" signal.
Readers and writers
StreamReader and StreamWriter add text on top of bytes, including encodings and lines. Write your method to take TextReader or TextWriter (their base classes) and it can work with a file, with memory, and with strings. StringReader and StringWriter are particularly handy for checks.
Console.WriteLine(CountLines(new StringReader("a\nb\nc\n")));
using (var file = new StreamWriter("data.txt"))
{
file.WriteLine("only line");
}
using (var reader = new StreamReader("data.txt"))
{
Console.WriteLine(CountLines(reader));
}
var output = new StringWriter();
Report(output, 3);
Console.Write(output.ToString());
Report(Console.Out, 4);
static int CountLines(TextReader reader)
{
int count = 0;
while (reader.ReadLine() is not null)
{
count++;
}
return count;
}
static void Report(TextWriter writer, int value)
{
writer.WriteLine($"Value: {value}");
}Check your prediction
3
1
Value: 3
Value: 4Look closely at Report. It doesn't care if it's given the console or a string. Accepting TextWriter makes its output easy to check, a trick you'll use again on Day 6.
CSV: harder than it looks
Splitting on commas works until a field contains a comma. Real CSV puts such fields in quotes, and a quote inside is doubled. For production, use a library such as CsvHelper. Here's why that's worth doing.
string line = "\"Smith, Ana\",42";
Console.WriteLine(line);
Console.WriteLine(line.Split(',').Length);
Console.WriteLine(Quote("Smith, Ana"));
Console.WriteLine(Quote("plain"));
Console.WriteLine(Quote("say \"hi\""));
static string Quote(string value)
{
if (!value.Contains(',') && !value.Contains('"'))
{
return value;
}
return $"\"{value.Replace("\"", "\"\"")}\"";
}Check your prediction
"Smith, Ana",42
3
"Smith, Ana"
plain
"say ""hi"""The next lesson's format, JSON, solves this same problem, and it has a parser in the standard library.
Fix it: Reading from the end
This writes text into a MemoryStream and reads it back. Predict the output, then run it.
using var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, leaveOpen: true))
{
writer.Write("saved text");
}
using var reader = new StreamReader(stream);
Console.WriteLine($"[{reader.ReadToEnd()}]");Check your prediction
[]A stream has one position, shared by reading and writing. After writing, it's at the end, so the reader starts there and finds nothing. Fix it.
Fix it
Move back to the start before reading:
using var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, leaveOpen: true))
{
writer.Write("saved text");
}
stream.Position = 0;
using var reader = new StreamReader(stream);
Console.WriteLine($"[{reader.ReadToEnd()}]");[saved text]Any code that writes to a stream and then hands it on to be read, such as a test that checks what was saved, needs this line. Forgetting it gives an empty result and no error.
Your turn
Number the lines
Write Number(TextReader input, TextWriter output), which copies its input to its output, with each line preceded by its number and a colon: 1: first. Lines that are blank keep their number but print nothing after it, with no trailing space (2:).
Test it twice: with a StringReader and a StringWriter, printing the result; and with a real file named in.txt, sending the output to Console.Out.
When it works, it prints:
1: first
2:
3: third
1: from fileConsole.WriteLine("Start here");Hint 1: the idea
The method needs no file names at all. It reads with ReadLine until null, and it writes with WriteLine.
Hint 2: a first step
Get the StringReader version working first, with a counter and a while loop. Handle the blank-line case with a conditional.
Show one solution
#nullable enable
var output = new StringWriter();
Number(new StringReader("first\n\nthird\n"), output);
Console.Write(output.ToString());
File.WriteAllText("in.txt", "from file\n");
using (var file = new StreamReader("in.txt"))
{
Number(file, Console.Out);
}
static void Number(TextReader input, TextWriter output)
{
int number = 0;
string? line;
while ((line = input.ReadLine()) is not null)
{
number++;
output.WriteLine(line.Length == 0 ? $"{number}:" : $"{number}: {line}");
}
}1: first
2:
3: third
1: from fileNumber accepts a TextReader and a TextWriter, not a file name, so the same method works on a string, a file or the console. That's what lets the first call run entirely in memory, which is how you'd test it. The empty-line case prints 2: without a trailing space, because $"{number}: {line}" would leave one invisible character behind.
Completion is saved in this browser only. It does not measure mastery.