Learn C# Β· 10/15

File I/O and Data Serialization

7 min read

10. File I/O and Data Serialization πŸ’Ύ

Welcome to the part of programming where things actually stick around!

Up until now, your variables have lived in the Random Access Memory (RAM). RAM is super fast, like a cheetah on espresso, but it has a terrible flaw: it has amnesia. The moment your program stops or your computer restarts, RAM forgets everything. Your high scores? Gone. Your user settings? Vanished.

To fix this, we need to talk to the Hard Drive (or SSD). It’s slower, like a wise old turtle, but it remembers forever (or until the disk corrupts, whichever comes first).

In this module, we will learn how to read/write files, handle messy file paths, and translate your C# objects into a language other systems can understand (JSON).


10.1 Reading and Writing Text Files πŸ“

Before we build complex databases, let's learn the ABCs: putting text into a file and getting it back out.

The Definition

File I/O (Input/Output) is the process of transferring data between your program's memory and an external storage device. In C#, this is primarily handled by the System.IO namespace.

The Problem

You have a string string secretMessage = "The password is 1234";. You close the app. You open the app. The string is gone. You need a way to persist this simple text.

The Solution

We use the File class for quick operations and StreamReader/StreamWriter for more robust, memory-efficient operations.

1. The "Quick and Dirty" Way (Small Files Only)

If you just need to save a small configuration or a short message, C# gives you helper methods that do everything in one line.

csharp
using System.IO;

// Writing
string content = "Hello, FreeCodeCamp!";
// This creates the file if it doesn't exist, or overwrites it if it does.
File.WriteAllText("message.txt", content); 

// Reading
string readContent = File.ReadAllText("message.txt");
Console.WriteLine(readContent); // Output: Hello, FreeCodeCamp!

Under the hood: WriteAllText opens the file, writes the data, closes the file, and flushes the memory buffers. It does it all for you.

2. The "Industry Standard" Way (Streaming) πŸ—οΈ

Imagine trying to read a 5GB log file using File.ReadAllText. Your program would try to load all 5GB into RAM at once and immediately crash with an OutOfMemoryException.

For real-world applications, we use Streams. A stream is like a water hose; you handle the data drop by drop (line by line) rather than drinking the whole ocean at once.

csharp
using System.IO;

string bigFilePath = "system_logs.txt";

// WRITING with StreamWriter
// The 'using' statement is CRITICAL. It ensures the file is closed 
// and memory is freed even if the code crashes halfway through.
using (StreamWriter writer = new StreamWriter(bigFilePath))
{
    writer.WriteLine("Log Entry 1: System started.");
    writer.WriteLine("Log Entry 2: User logged in.");
}

// READING with StreamReader
if (File.Exists(bigFilePath))
{
    using (StreamReader reader = new StreamReader(bigFilePath))
    {
        string line;
        // Read the file line by line until the end (null)
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine($"Processing: {line}");
        }
    }
}

Fun Fact: Forgetting to close a file stream is a classic rookie mistake. It "locks" the file, meaning no one else (not even you) can delete or move it until you restart your computer. The using block prevents this embarrassment.


10.2 Working with Directories and File Paths πŸ“‚

The Definition

File Paths are string representations of the location of a file on a disk. Directories are the containers (folders) that hold files.

The Problem

You write code like this:
string path = "C:\Users\Kevin\Documents\data.txt";

Then you send your app to your friend, Sarah. Her computer crashes. Why?

  1. Her name isn't Kevin.
  2. If she uses a Mac or Linux, they use forward slashes / instead of backslashes \.
  3. Hardcoding paths is the root of the "It works on my machine" syndrome.

The Solution

Use Path.Combine and the Environment special folders. This makes your path logic dynamic and cross-platform.

csharp
using System.IO;

// Get the path to the user's "My Documents" folder dynamically
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Define a custom folder name
string appFolder = "FreeCodeCampApp";

// ❌ BAD: string fullPath = folderPath + "\\" + appFolder; 
// βœ… GOOD: Let C# figure out if it needs \ or /
string fullPath = Path.Combine(folderPath, appFolder);

// Check if directory exists, if not, create it
if (!Directory.Exists(fullPath))
{
    Directory.CreateDirectory(fullPath);
    Console.WriteLine($"Created directory at: {fullPath}");
}

// Create a file path inside that directory
string filePath = Path.Combine(fullPath, "settings.txt");
Console.WriteLine($"Final file location: {filePath}");

Why this matters: In the industry, apps run on Cloud Servers (usually Linux) and Developer Laptops (Windows/Mac). Path.Combine ensures your app doesn't break just because the operating system changed.


10.3 JSON Serialization: Converting Objects to Text πŸ“¦

Now, we have a bigger problem. We know how to save strings... but we don't program in just strings. We use Objects.

The Problem

You have a User object:

csharp
public class User 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<string> Hobbies { get; set; }
}

If you try File.WriteAllText("user.txt", myUser.ToString());, you will just save the text "MyNamespace.User" into the file. That's useless. You need to save the data inside the object.

The Solution: JSON

JSON (JavaScript Object Notation) is the universal language of the web. It's lightweight text that looks almost exactly like C# object initialization.

Serialization is the process of converting an object instance into a format (like a JSON string) that can be stored or transmitted.

The Code

Modern .NET uses System.Text.Json (it's built-in and super fast).

csharp
using System.Text.Json; // The modern standard namespace

// 1. Create the data
var user = new User 
{ 
    Id = 1, 
    Name = "Quincy Larson", 
    Hobbies = new List<string> { "Coding", "Teaching", "Pizza" } 
};

// 2. Serialize options (Optional, but makes it readable for humans)
var options = new JsonSerializerOptions { WriteIndented = true };

// 3. Serialize to String
string jsonString = JsonSerializer.Serialize(user, options);

// 4. Save to file (using what we learned in 10.1!)
File.WriteAllText("user_data.json", jsonString);

Console.WriteLine(jsonString);

Output in file:

json
{
  "Id": 1,
  "Name": "Quincy Larson",
  "Hobbies": [
    "Coding",
    "Teaching",
    "Pizza"
  ]
}

Industry Note: You might see old tutorials using Newtonsoft.Json. While it's still popular, System.Text.Json is the new standard provided by Microsoft. It's much faster and doesn't require installing external packages for basic tasks.


10.4 JSON Deserialization: Rebuilding Objects from Text πŸ—οΈ

The Definition

Deserialization is the reverse process: taking data stored in a format (like JSON) and reconstructing it into an object in memory.

The Problem

You have a text file named user_data.json. To C#, this is just a long string of characters. You can't say jsonString.Name because strings don't have a Name property. You need to convert it back to a User class instance.

The Solution

We use JsonSerializer.Deserialize<Type>.

csharp
using System.Text.Json;

// 1. Read the text from disk
string jsonFromFile = File.ReadAllText("user_data.json");

// 2. Deserialize back into a User object
// Note: The properties in the JSON must match the properties in the Class!
User loadedUser = JsonSerializer.Deserialize<User>(jsonFromFile);

// 3. Use the object
Console.WriteLine($"Welcome back, {loadedUser.Name}!"); 
Console.WriteLine($"First hobby: {loadedUser.Hobbies[0]}");

Vital Concept: Case Sensitivity

JSON is traditionally camelCase (firstName), while C# properties are PascalCase (FirstName).

System.Text.Json is strict by default. If your JSON says "name": "Alice" and your C# class has public string Name {get;set;}, it might return null because 'n' and 'N' are different.

The Fix:
Configure the options to be case-insensitive (highly recommended for robustness).

csharp
var options = new JsonSerializerOptions 
{ 
    PropertyNameCaseInsensitive = true 
};

User loadedUser = JsonSerializer.Deserialize<User>(jsonFromFile, options);

Summary Checklist βœ…

  1. File.WriteAllText: Good for quick, small text dumps.
  2. StreamWriter/Reader: Mandatory for large files or frequent access to prevent memory crashes.
  3. Using Statement: Always wrap streams in using (...) to prevent file locks.
  4. Path.Combine: Never manually concatenate strings for file paths. Let .NET handle the slashes.
  5. Serialization: Object -> JSON String (saving).
  6. Deserialization: JSON String -> Object (loading).

πŸ“š Further Reading & References


Now go forth and save your data, before the next power outage wipes your RAM! πŸƒπŸ’¨

Challenge

Challenge: C# User Settings Persistence

You are tasked with creating a SettingsManager class in C# to handle saving and loading user preferences for an application. This involves serializing a C# object to a JSON file and deserializing it back.

Your task is to implement two methods within the provided SettingsManager class: SaveSettings and LoadSettings.

UserSettings Class Definition:

The object you will be working with is an instance of the UserSettings class, which is already defined for you. It has the following structure:

csharp
public class UserSettings
{
    public string Username { get; set; }
    public string Theme { get; set; }
    public DateTime LastLogin { get; set; }
    public List<string> FavoriteItems { get; set; }
}

Requirements:

  1. SaveSettings(UserSettings settings, string fileName) Method:

    • This method must dynamically determine the path to the user's 'MyDocuments' folder.
    • It should ensure a subdirectory named AppSettings exists within the 'MyDocuments' folder. If it doesn't exist, the method must create it.
    • Construct the full file path for the given fileName inside the AppSettings directory using the appropriate Path method to ensure cross-platform compatibility.
    • Serialize the incoming settings object into a human-readable (indented) JSON string.
    • Using the industry-standard stream-based approach for file I/O, write the JSON string to the file. Ensure that file resources are properly disposed of to prevent file locking.
  2. LoadSettings(string fileName) Method:

    • This method must construct the full file path to the settings file, identical to the logic in SaveSettings.
    • If the settings file does not exist at the constructed path, the method should return null.
    • Using a stream, read the entire content of the JSON file.
    • Deserialize the JSON string back into a UserSettings object. The method must be robust enough to handle JSON properties written in camelCase (e.g., "username") and correctly map them to the PascalCase properties of the C# class.
    • Return the deserialized UserSettings object.

Expected result

The user should correctly implement the SaveSettings and LoadSettings methods.

For SaveSettings:

The implementation must:

  • Use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) to get the base directory.
  • Use Path.Combine() to create the path for the AppSettings subdirectory and the final file path.
  • Check for the directory's existence with Directory.Exists() and create it with Directory.CreateDirectory() if needed.
  • Call JsonSerializer.Serialize() on the settings object, passing a JsonSerializerOptions instance with WriteIndented = true.
  • Wrap the file writing logic in a using (StreamWriter writer = new StreamWriter(filePath)) block to write the JSON string to the file.

For LoadSettings:

The implementation must:

  • Construct the full file path using the same Environment.GetFolderPath and Path.Combine logic.
  • Use File.Exists() to check for the file and return null if it's not found.
  • Wrap the file reading logic in a using (StreamReader reader = new StreamReader(filePath)) block.
  • Read the file's content into a string, for example with reader.ReadToEnd().
  • Call JsonSerializer.Deserialize<UserSettings>(), passing the JSON string and a JsonSerializerOptions instance with PropertyNameCaseInsensitive = true to handle potential casing mismatches between the JSON and the C# class.
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.