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
File.WriteAllTextandAppendAllTextcreate and extend.File.ReadAllLineshands the file back as a string array.Path.Combinebuilds paths that survive the platform separator.
Keywords and builtins used here
foreachinvar
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.
Step 2 of 3 in Errors & files, step 26 of 29 in Language basics.