File I/O
Save and load data as JSON.
Save the Library to a file
A Save(string path) method turns the _books list into text with JsonSerializer.Serialize and writes it to a file with File.WriteAllText. The library then persists across restarts.
The JsonSerializer class comes from the System.Text.Json namespace and the File class from System.IO. Serialization writes each book's properties as key-value pairs.
Writing with the File class
File.WriteAllText(path, text) writes the whole text to a file at once; it overwrites an existing file or creates a new one. File.ReadAllText(path) reads it back.
The save flow: produce text with Serialize, then write it with WriteAllText. The restore flow: read with ReadAllText, then turn back into an object with Deserialize<List<Book>>.
Exercise Add the Save method
Add a Save(string path) method to the Library class below: it turns _books into text with JsonSerializer.Serialize and writes it with File.WriteAllText. In Main add a book, call Save and print "Saved".
Show example solution
Write public void Save(string path) { string text = JsonSerializer.Serialize(_books); File.WriteAllText(path, text); }. In Main add lib.Save("books.txt"); Console.WriteLine("Saved");
Example solution:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
class Book
{
public string Title { get; set; }
public string Author { get; set; }
}
class Library
{
private List<Book> _books = new List<Book>();
public void Add(Book b) => _books.Add(b);
public int Count => _books.Count;
public IEnumerable<Book> FindByAuthor(string author)
{
return _books.Where(b => b.Author == author);
}
public void Save(string path)
{
string text = JsonSerializer.Serialize(_books);
File.WriteAllText(path, text);
}
}
class Program
{
static void Main()
{
var lib = new Library();
lib.Add(new Book { Title = "Crime and Punishment", Author = "Dostoevsky" });
lib.Save("books.txt");
Console.WriteLine("Saved");
}
}
Test yourself
-
What does JsonSerializer.Serialize do?
- Turns text into an object
- Deletes a file
- Sorts a list
- Turns an object into text
Show answer
Turns an object into text — Correct. Serialize turns an object into text.
-
Complete the Serialize call
string text = JsonSerializer.____(_books);Show answer
string text = JsonSerializer.Serialize(_books); -
Match the method to its role
- Serialize
- Object to text
- Deserialize
- Text to object
- WriteAllText
- Write to file
- ReadAllText
- Read from file