×

c# · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.