LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

File Handling and JSON Serialization in C#

When our application runs, all data lives in RAM and disappears when the program closes. To keep user profiles, game scores, or settings across sessions, we convert our objects into text using serialization and write them into files on disk.

1Work with Files and JSON

Hi friends, in this article we will learn how to read and write files in C#, and how to convert objects into JSON. File handling lets an application store information beyond its current run. JSON is a text format commonly used to exchange and save structured data. These skills are useful in configuration files, reports, small data stores and API integrations.

2Think About an Online Order

Imagine an online shopping app. After a customer places an order, the app needs to save details such as the order number, customer name and amount. It can convert the order object into JSON and write that text to a file. Later, the app can read the file and rebuild the object.

This is the basic flow: object to JSON, JSON to file, file back to JSON, and JSON back to an object.

3Learn the Important Building Blocks

File class

System.IO.File provides methods such as WriteAllText() and ReadAllText() for simple text files.

Serialization

Serialization converts an object into a format that can be stored or transferred. JsonSerializer.Serialize() converts a C# object into JSON text.

Deserialization

Deserialization converts JSON text back into a C# object using JsonSerializer.Deserialize().

JSON options

WriteIndented = true makes JSON easier for people to read by adding line breaks and indentation.

Remember JSON property names and values are text. Numbers remain numeric values, and strings must be enclosed in quotation marks.

4Save and Load an Order

This complete console example creates an order, serializes it, saves it to order.json, reads the file and deserializes the JSON.

Program.csC#
using System;
using System.IO;
using System.Text.Json;

var order = new Order
{
    OrderId = 501,
    Customer = "Ananya",
    Amount = 2499.50
};

var options = new JsonSerializerOptions
{
    WriteIndented = true
};

string json = JsonSerializer.Serialize(order, options);
File.WriteAllText("order.json", json);
Console.WriteLine("Order saved.");

string fileContent = File.ReadAllText("order.json");
var loadedOrder =
    JsonSerializer.Deserialize<Order>(fileContent);

Console.WriteLine($"Loaded: {loadedOrder!.OrderId}, {loadedOrder.Customer}, {loadedOrder.Amount:F2}");

class Order
{
    public int OrderId { get; set; }
    public string Customer { get; set; } = "";
    public decimal Amount { get; set; }
}
Pro Tip Run this in a .NET console project. The file is created in the application's current working directory.

5See What the Program Produces

The first message confirms the file write. The next message shows the values read back from the JSON file.

Console Output
Order saved.
Loaded: 501, Ananya, 2499.50

The generated order.json contains the order properties as readable JSON text.

order.json
{
  "OrderId": 501,
  "Customer": "Ananya",
  "Amount": 2499.50
}
Common Mistake Do not assume a file always exists. Production code should handle missing files, invalid JSON and access errors.

6Watch File Handling in VS Code

Follow the source lines as the program serializes the order, writes the JSON, reads it and prints the loaded values.

Program.cs - Visual Studio Code
 
Program.cs
1using System;
2using System.IO;
3using System.Text.Json;
4
5var order = new Order
6{
7 OrderId = 501,
8 Customer = "Ananya",
9 Amount = 2499.50
10};
11
12var options = new JsonSerializerOptions
13{
14 WriteIndented = true
15};
16
17string json = JsonSerializer.Serialize(order, options);
18File.WriteAllText("order.json", json);
19Console.WriteLine("Order saved.");
20
21string fileContent = File.ReadAllText("order.json");
22var loadedOrder =
23 JsonSerializer.Deserialize<Order>(fileContent);
24
25Console.WriteLine($"Loaded: {loadedOrder!.OrderId}, {loadedOrder.Customer}, {loadedOrder.Amount:F2}");
26
27class Order
28{
29 public int OrderId { get; set; }
30 public string Customer { get; set; } = "";
31 public decimal Amount { get; set; }
32}
PROBLEMSOUTPUTDEBUG CONSOLETERMINAL
PS C:\Projects\Demo> dotnet run
Order saved.
Loaded: 501, Ananya, 2499.50
PS C:\Projects\Demo>
Ln 17, Col 1UTF-8C#Ready

7What Should You Remember?

File handling stores and retrieves data using paths and text. JSON serialization makes C# objects easy to store or exchange. Deserialization rebuilds an object from JSON. Always consider file paths, permissions and invalid data when building real applications.

  • Write: Use File.WriteAllText() to save text.
  • Read: Use File.ReadAllText() to load text.
  • Convert: Use JsonSerializer to serialize and deserialize objects.

8Practice These Interview Questions

Q1Easy

What is file handling in C#?

It means creating, reading, writing and managing files from an application. The System.IO namespace provides common file APIs.

Q2Easy

What is JSON serialization?

It converts an object into JSON text. In .NET, JsonSerializer.Serialize() performs this conversion.

Q3Medium

What is the difference between serialization and deserialization?

Serialization converts an object into JSON. Deserialization reads JSON text and converts it back into an object.

Q4Medium

What does WriteIndented do?

It formats the generated JSON with indentation and line breaks. This improves readability but does not change the represented data.

Q5Hard

How should an application handle a missing file?

Check with File.Exists() when appropriate, and handle expected I/O exceptions. The right response depends on whether the file is optional or required.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.