File IO and Serialization

Back

Loading concept...

Data Processing: File IO and Serialization in C#

The Magic Filing Cabinet 🗄️

Imagine your computer is a giant magical filing cabinet. Inside this cabinet, you can:

  • Create new folders to organize your stuff
  • Put papers (files) inside those folders
  • Read what’s written on those papers
  • Change what’s written or throw papers away
  • Find exactly where things are using addresses (paths)

C# gives you special tools to work with this filing cabinet. Let’s explore them!


📁 File Operations: Your Paper Handler

Think of files like pieces of paper in your filing cabinet. You can:

  • Write on new paper
  • Read what’s already written
  • Add more words to existing paper
  • Throw paper in the trash

Creating and Writing to a File

// Write a message to a file
// Like writing on a new piece of paper
File.WriteAllText(
    "hello.txt",
    "Hello, World!"
);

What happens? C# creates a file called hello.txt and writes “Hello, World!” inside it.

Reading from a File

// Read what's written on the paper
string message = File.ReadAllText(
    "hello.txt"
);
// message now contains "Hello, World!"

What happens? C# opens the file and reads everything inside, giving it back to you as text.

Adding More to a File

// Add more words to existing paper
File.AppendAllText(
    "diary.txt",
    "Today was fun!\n"
);

What happens? Instead of erasing what’s there, C# adds your new text at the end.

Checking if a File Exists

// Is there paper with this name?
if (File.Exists("hello.txt"))
{
    Console.WriteLine("Found it!");
}

Deleting a File

// Throw the paper away
File.Delete("hello.txt");

Copying and Moving Files

// Make a photocopy
File.Copy("original.txt", "copy.txt");

// Move paper to new location
File.Move("old.txt", "newfolder/old.txt");

📂 Directory Operations: Your Folder Manager

Directories are like folders in your filing cabinet. They help you organize your files.

Creating a Folder

// Make a new folder
Directory.CreateDirectory("MyPhotos");

// Make nested folders too!
Directory.CreateDirectory(
    "Documents/School/Math"
);

What happens? C# creates all the folders you need, even folders inside folders!

Checking if a Folder Exists

if (Directory.Exists("MyPhotos"))
{
    Console.WriteLine("Folder is here!");
}

Listing What’s Inside

// See all files in a folder
string[] files = Directory.GetFiles(
    "MyPhotos"
);

// See all folders inside
string[] folders = Directory.GetDirectories(
    "Documents"
);

Deleting a Folder

// Delete empty folder
Directory.Delete("EmptyFolder");

// Delete folder with everything inside
Directory.Delete("OldStuff", true);

⚠️ Warning: The true means “delete everything inside too!” Be careful with this!

Getting Current Location

// Where am I right now?
string here = Directory.GetCurrentDirectory();

🛤️ Path Operations: Your Address Finder

Paths are like addresses that tell you exactly where something is. Just like “123 Main Street, Apartment 4” tells you where a friend lives!

Building Paths Safely

// Combine folder and file names
string fullPath = Path.Combine(
    "Documents",
    "Reports",
    "sales.txt"
);
// Result: "Documents/Reports/sales.txt"

Why use Path.Combine? Different computers use different symbols (/ or ). Path.Combine picks the right one automatically!

Getting Parts of a Path

string path = "/home/user/photo.jpg";

// Just the filename
string name = Path.GetFileName(path);
// Result: "photo.jpg"

// Filename without extension
string nameOnly = Path.GetFileNameWithoutExtension(
    path
);
// Result: "photo"

// Just the extension
string ext = Path.GetExtension(path);
// Result: ".jpg"

// Just the folder
string folder = Path.GetDirectoryName(path);
// Result: "/home/user"

Creating Temporary Files

// Get a safe place for temporary files
string tempFolder = Path.GetTempPath();

// Get a unique temporary filename
string tempFile = Path.GetTempFileName();

Checking Path Info

// Does this path have an extension?
bool hasExt = Path.HasExtension("photo.jpg");
// Result: true

// Is this a full address or partial?
bool isRooted = Path.IsPathRooted("/home/user");
// Result: true

🔄 JSON Serialization: Turning Objects into Text

Imagine you have a toy box with your favorite toys. You want to tell your friend exactly what’s inside, so they can build the same toy box. You need to write down a list that describes everything perfectly.

JSON (JavaScript Object Notation) is like that list. It turns your C# objects into text that can be:

  • Saved to files
  • Sent over the internet
  • Read back later to recreate your objects

What JSON Looks Like

{
  "name": "Max",
  "age": 8,
  "toys": ["ball", "robot", "puzzle"]
}

It’s just text that describes things using:

  • { } for objects (like a box)
  • [ ] for lists (like an array)
  • "key": "value" for properties

Converting Object to JSON (Serialization)

using System.Text.Json;

// Your toy (a C# class)
public class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Create a pet
Pet myPet = new Pet
{
    Name = "Fluffy",
    Age = 3
};

// Turn it into JSON text
string json = JsonSerializer.Serialize(myPet);
// Result: {"Name":"Fluffy","Age":3}

Converting JSON to Object (Deserialization)

// JSON text (maybe from a file)
string json = "{\"Name\":\"Buddy\",\"Age\":5}";

// Turn it back into a Pet object
Pet loadedPet = JsonSerializer.Deserialize<Pet>(
    json
);

Console.WriteLine(loadedPet.Name); // "Buddy"

Pretty Printing JSON

var options = new JsonSerializerOptions
{
    WriteIndented = true
};

string prettyJson = JsonSerializer.Serialize(
    myPet,
    options
);

This makes the JSON easier to read with nice spacing!

Saving and Loading from Files

// Save pet to file
string json = JsonSerializer.Serialize(myPet);
File.WriteAllText("pet.json", json);

// Load pet from file
string loaded = File.ReadAllText("pet.json");
Pet savedPet = JsonSerializer.Deserialize<Pet>(
    loaded
);

🎯 Putting It All Together

Here’s a real example that uses everything we learned:

using System.Text.Json;

public class GameScore
{
    public string Player { get; set; }
    public int Score { get; set; }
}

// Create scores folder
string scoresDir = Path.Combine(
    Directory.GetCurrentDirectory(),
    "Scores"
);
Directory.CreateDirectory(scoresDir);

// Save a score
var score = new GameScore
{
    Player = "Alex",
    Score = 9500
};

string filePath = Path.Combine(
    scoresDir,
    "highscore.json"
);

string json = JsonSerializer.Serialize(score);
File.WriteAllText(filePath, json);

// Later: Load the score
if (File.Exists(filePath))
{
    string data = File.ReadAllText(filePath);
    var loaded = JsonSerializer.Deserialize<GameScore>(
        data
    );
    Console.WriteLine(quot;{loaded.Player}: {loaded.Score}");
}

🗺️ Visual Summary

graph TD A["Your C&#35; Program"] --> B["File Operations"] A --> C["Directory Operations"] A --> D["Path Operations"] A --> E["JSON Serialization"] B --> B1["Read Files"] B --> B2["Write Files"] B --> B3["Copy/Move/Delete"] C --> C1["Create Folders"] C --> C2["List Contents"] C --> C3["Delete Folders"] D --> D1["Build Paths"] D --> D2["Get Parts"] D --> D3["Temp Files"] E --> E1["Object to JSON"] E --> E2["JSON to Object"] E --> E3["Save/Load Files"]

🌟 Key Takeaways

What Tool Example
Read/Write files File File.WriteAllText()
Manage folders Directory Directory.CreateDirectory()
Build addresses Path Path.Combine()
Convert objects JsonSerializer Serialize() / Deserialize()

🚀 You Did It!

Now you know how to:

  • Read and write files like a pro
  • Create and manage folders to stay organized
  • Build safe paths that work everywhere
  • Turn objects into JSON and back again

Your programs can now remember things, save data, and communicate with the outside world. That’s powerful stuff! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.