typestar

Files in C#

Whole-file reads and writes in single calls.

var path = Path.Combine(Path.GetTempPath(), "notes.txt");

File.WriteAllText(path, "first line\nsecond line\n");
File.AppendAllText(path, "third line\n");

foreach (var line in File.ReadAllLines(path))
{
    Console.WriteLine($"> {line}");
}
Console.WriteLine(File.Exists(path));
File.Delete(path);

How it works

  1. File.WriteAllText and AppendAllText create and extend.
  2. File.ReadAllLines hands the file back as a string array.
  3. Path.Combine builds paths that survive the platform separator.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
294
Tokens
74
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 2 of 3 in Errors & files, step 26 of 29 in Language basics.

← Previous Next →

Files in other languages