c# · level 2 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Save one record per line, then each line up.
Real apps save many records, one per line. A file does this with commas between the parts: Rex,dog,3. adds text to the end of a file instead of replacing it, and makes the file if it is missing.
gives the file back as an array of strings, one per line. line.Split(",") cuts a line at every comma, so parts[0] is the name. Every part is text, so turn numbers back with int.Parse or decimal.Parse.
using System;
using System.IO;
File.WriteAllText("pets.csv", "Rex,dog,3\n");
File.AppendAllText("pets.csv", "Tibbles,cat,7\n");
File.AppendAllText("pets.csv", "Nibbles,hamster,1\n");
foreach (string line in File.ReadAllLines("pets.csv"))
{
string[] parts = line.Split(",");
int age = int.Parse(parts[2]);
Console.WriteLine($"{parts[0]} the {parts[1]} is {age}");
} End every line you append with \n, so the next record starts on a new line.
guess first
Write, add, write, add. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.IO;
File.WriteAllText("log.csv", "Mon,5\n");
File.AppendAllText("log.csv", "Tue,8\n");
File.WriteAllText("log.csv", "Wed,2\n");
File.AppendAllText("log.csv", "Thu,6\n");
int total = 0;
foreach (string line in File.ReadAllLines("log.csv"))
{
total = total + int.Parse(line.Split(",")[1]);
}
Console.WriteLine(total);
your turn
Your turn. Log your runs.
On line 7, add a run of your own as a CSV line, a day and the kilometres, like Fri,6.5. On line 11, cut each line into parts at the comma. Press run.
output
press run to see what happens
fix it
Only one job got saved. Fix it!
output
press run to see what happens
- Only fix bike survives. What does
File.WriteAllTexton line 7 do to what was already in the file? - Each turn of the loop replaces the whole file. You want to add to the end instead.
- Change
File.WriteAllTexttoFile.AppendAllTexton line 7, then press run.
nailed it
your records are saved line by line. :D
File.AppendAllTextadds to the end of a file.File.ReadAllLinesgives one string per line.Split(",")cuts a CSV line into its parts.
new words in your collection
- CSV
- File.AppendAllText
- File.ReadAllLines
- Split
This lesson isn’t saved. A free account remembers every lesson you finish.