C#
Summary - File I/O
Combine ReadAllText, StreamWriter and Exists to write a notes app.
Summary - File I/O
In this group you learned file operations: ReadAllText reads the whole file, WriteAllText writes, ReadAllLines gives a line array, StreamReader/StreamWriter stream, Exists checks, Delete removes.
In the final lesson you will build a small notes app: save a note to a file, read and show it if it exists, otherwise print a welcome message. This is the foundation of a real console tool.
Exercise Notes app: save and read
First save the note with File.WriteAllText("note.txt", "Lovely weather today");. Then if File.Exists("note.txt") is true, read it with File.ReadAllText("note.txt") and print with Console.WriteLine; otherwise print Console.WriteLine("No note");.
Show example solution
First save with File.WriteAllText("note.txt", "Lovely weather today");. Then check with if (File.Exists("note.txt")); if true, var text = File.ReadAllText("note.txt"); Console.WriteLine(text);, else Console.WriteLine("No note");.
Example solution:
using System;
using System.IO;
class Program
{
static void Main()
{
File.WriteAllText("note.txt", "Lovely weather today");
if (File.Exists("note.txt"))
{
var text = File.ReadAllText("note.txt");
Console.WriteLine(text);
}
else
{
Console.WriteLine("No note");
}
}
}
Exercise Keep a diary with StreamWriter
Inside a using (var sw = new StreamWriter("diary.txt")) block, write two lines with sw.WriteLine: "Morning" and "Evening". Then read with File.ReadAllLines("diary.txt") and print each line in a foreach loop.
Show example solution
First inside using (var sw = new StreamWriter("diary.txt")) write two WriteLine calls. Then foreach (var line in File.ReadAllLines("diary.txt")) Console.WriteLine(line);.
Example solution:
using System;
using System.IO;
class Program
{
static void Main()
{
using (var sw = new StreamWriter("diary.txt"))
{
sw.WriteLine("Morning");
sw.WriteLine("Evening");
}
foreach (var line in File.ReadAllLines("diary.txt"))
{
Console.WriteLine(line);
}
}
}
Test yourself
-
Which for a large file?
- File.ReadAllText
- File.Exists
- File.Delete
- StreamReader
Show answer
StreamReader — Correct. StreamReader provides stream-based reading for large files; it does not load the whole file into memory.
-
Match each method to its purpose
- ReadAllText
- Reads whole file
- WriteAllText
- Overwrites
- StreamReader
- Streams read
- Exists
- Checks presence
Next lesson: JsonSerializer basics