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.
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.
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; }
}
5See What the Program Produces
The first message confirms the file write. The next message shows the values read back from the JSON file.
Order saved. Loaded: 501, Ananya, 2499.50
The generated order.json contains the order properties as readable JSON text.
{
"OrderId": 501,
"Customer": "Ananya",
"Amount": 2499.50
}
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.
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
JsonSerializerto serialize and deserialize objects.
8Practice These Interview Questions
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.
What is JSON serialization?
It converts an object into JSON text. In .NET, JsonSerializer.Serialize() performs this conversion.
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.
What does WriteIndented do?
It formats the generated JSON with indentation and line breaks. This improves readability but does not change the represented data.
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.