You write and read files with the quick methods of the File class and with StreamWriter and StreamReader, and learn why CSV breaks under regional settings that use a decimal comma and how InvariantCulture fixes it.
A program that takes measurements should not lose its data when it closes. A temperature logger takes a value every minute and writes it to a file; the next day you open that file and find the average, the maximum and the moments of alarm. In engineering the common language for this is CSV (comma-separated values): Excel opens it, Python reads it, and your C# program can both write and read it. Most file work in .NET is done with the File, StreamWriter and StreamReader classes in the System.IO namespace, which new projects include automatically.
The quick way: the File class
For small files the one-line methods of the File class are enough: each one opens the file, does its job and closes it.
string path = "notes.txt";
File.WriteAllText(path, "Panel MDP-1 inspected\n"); // creates it, or overwrites
File.AppendAllText(path, "Fuses intact\n"); // adds to the end
File.AppendAllLines(path, new[] { "Earthing: 0.8 ohm", "Result: PASS" });
string[] lines = File.ReadAllLines(path);
Console.WriteLine($"{lines.Length} lines read:");
foreach (string s in lines)
Console.WriteLine(" " + s);
Console.WriteLine(File.Exists(path));
Console.WriteLine(File.Exists("missing.txt"));
4 lines read:
Panel MDP-1 inspected
Fuses intact
Earthing: 0.8 ohm
Result: PASS
True
False
A file name on its own is a relative path: the file is written to whichever folder the program is running in at that moment. When you run with dotnet run, that is the project folder.
The hidden trap of CSV: the decimal separator
Many regional settings, such as Turkish or German, write 21.5 as 21,5 with a comma. In CSV, however, the comma separates columns. If such a machine writes the temperature directly as $"{minute},{temperature}", you get a broken three-column line like 0,21,5. The fix: use the settings-independent invariant culture (CultureInfo.InvariantCulture) when writing to and reading from files. This culture uses a point for decimals on every machine.
using System.Globalization;
double d = 21.5;
Console.WriteLine($"German settings: {d.ToString(new CultureInfo("de-DE"))}");
Console.WriteLine($"Invariant culture: {d.ToString(CultureInfo.InvariantCulture)}");
German settings: 21,5
Invariant culture: 21.5
The rule is simple: use the local settings when showing numbers to people, and the invariant culture when handing them to a file or another program.
Writing CSV with StreamWriter
If you write many lines, or produce them in a loop, StreamWriter is a better fit. It collects data in memory first and then writes it to disk in bulk. That is why it must be closed when you are done; the safest way is a using block.
using System.Globalization;
var inv = CultureInfo.InvariantCulture;
double[] temperatures = { 21.5, 22.25, 23.0, 35.75, 22.5 };
using (var writer = new StreamWriter("sensor.csv"))
{
writer.WriteLine("minute,temperature");
for (int i = 0; i < temperatures.Length; i++)
writer.WriteLine($"{i},{temperatures[i].ToString(inv)}");
} // when the block ends the file is closed and the data is on disk
Console.WriteLine(File.ReadAllText("sensor.csv"));
minute,temperature
0,21.5
1,22.25
2,23
3,35.75
4,22.5
We deliberately chose the braced using (...) { } block instead of using var here. using var closes the object at the end of its enclosing scope, which in top-level code means the end of the program. If you are going to read the file back right away in the same program, the writing block must already be closed.
Reading line by line with StreamReader
Real log files contain broken lines: the sensor wrote "ERROR", or the connection dropped and a line was cut short. When reading, split each line with Split and check it with TryParse, so that one bad line does not crash the whole read.
using System.Globalization;
var inv = CultureInfo.InvariantCulture;
File.WriteAllLines("log.csv", new[]
{
"minute,temperature", "0,21.5", "1,22.25", "2,ERROR", "3,35.75", "4,22.5"
});
var values = new List<double>();
int faulty = 0;
using (var reader = new StreamReader("log.csv"))
{
reader.ReadLine(); // skip the header line
string? line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(',');
if (parts.Length == 2 && double.TryParse(parts[1], NumberStyles.Float, inv, out double t))
values.Add(t);
else
faulty++;
}
}
Console.WriteLine($"Valid: {values.Count}, faulty: {faulty}");
Console.WriteLine($"Average: {values.Average():F2} C, max: {values.Max()} C");
Valid: 4, faulty: 1
Average: 25.50 C, max: 35.75 C
We read the file with the invariant culture and showed the result on screen with the local settings; that is the rule above in action. ReadLine returns null at the end of the file, and the loop ends there. Because this method does not load the whole file into memory, it works even for gigabyte-sized logs.
A round trip with records
The record type from the previous lesson gets along very well with file work. Let us write readings to a folder, read them back, and prove with record equality that nothing was lost:
using System.Globalization;
var inv = CultureInfo.InvariantCulture;
var readings = new List<Reading> { new("CH1", 3.31), new("CH2", 4.98), new("CH1", 3.29) };
Directory.CreateDirectory("logs"); // leaves it alone if it exists
string path = Path.Combine("logs", "readings.csv"); // separator that fits the OS
File.WriteAllLines(path, readings.Select(r => $"{r.Channel},{r.Value.ToString(inv)}"));
var back = File.ReadLines(path)
.Select(s => s.Split(','))
.Select(p => new Reading(p[0], double.Parse(p[1], inv)))
.ToList();
Console.WriteLine(back.SequenceEqual(readings));
Console.WriteLine(back[1]);
record Reading(string Channel, double Value);
True
Reading { Channel = CH2, Value = 4.98 }
Path.Combine joins paths correctly with \ on Windows and / on Linux; do not glue paths by hand with + "\\" +. SequenceEqual compares two lists element by element; since records compare by value, the data written and the data read back came out exactly the same.
Common mistakes
- Forgetting the culture: Writing and reading CSV with local settings means the program works on your machine and reads wrong values on a customer's machine. For files, always use
CultureInfo.InvariantCulture. - Not closing the StreamWriter: Without
usingorDispose, the last buffered lines may never reach the disk and the file stays locked. When you try to open the same file elsewhere, you get "the file is being used by another process". - Not knowing where a relative path goes: If you run the program by double-clicking it or from another folder instead of with
dotnet run, the file is written somewhere else. For important files use a full path, or combine the path withAppContext.BaseDirectory(the folder the program lives in).
Exercise
Create a panel temperature log (header minute,temperature, 5 lines: 24.5, 31.0, 29.5, 33.5, 28.0). Read it and write a three-line report to report.txt: the number of readings, the average temperature, and how many times and in which minutes 30 degrees was exceeded. Then print the report to the screen.
Hint: File.ReadLines(...).Skip(1) skips the header. If you turn each line into a (Minute, Temperature) tuple, filtering with LINQ gets easy. Since people will read the report, you can write its numbers with the local settings.
Solution
using System.Globalization;
var inv = CultureInfo.InvariantCulture;
File.WriteAllLines("panel.csv", new[] { "minute,temperature", "0,24.5", "1,31.0", "2,29.5", "3,33.5", "4,28.0" });
var records = File.ReadLines("panel.csv")
.Skip(1)
.Select(s => s.Split(','))
.Select(p => (Minute: int.Parse(p[0]), Temperature: double.Parse(p[1], inv)))
.ToList();
var hot = records.Where(r => r.Temperature > 30).Select(r => r.Minute).ToList();
using (var report = new StreamWriter("report.txt"))
{
report.WriteLine($"Number of readings: {records.Count}");
report.WriteLine($"Average: {records.Average(r => r.Temperature):F2} C");
report.WriteLine($"Above 30 C: {hot.Count} times (minutes {string.Join(", ", hot)})");
}
Console.Write(File.ReadAllText("report.txt"));
Number of readings: 5
Average: 29.30 C
Above 30 C: 2 times (minutes 1, 3)
With that you have built the whole chain of collecting, saving, reading and reporting data; this is the skeleton of real data logger software.
You can now make your data permanent. In the next lesson we move on to async and await, which stop the program from freezing while it waits for slow devices.
// Spot the bug +10 XP
Exactly one line below is wrong. Click the faulty line.
Line 7 calls double.Parse without specifying a culture. On a computer with Turkish or German regional settings, the point is not the decimal separator but a group separator; "3.3" is read as 33 and the screen shows "CH1: 33 V". On an English machine the bug stays hidden, which makes it even more dangerous. A file format must not depend on the machine: double.Parse(parts[1], CultureInfo.InvariantCulture).
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.


