C# File I/O — Complete Beginner Guide
Learning Objectives
- Read and write text files with File helpers
- Stream large text safely with StreamReader and StreamWriter
- Serialize objects to JSON and back
- Handle missing files and bad data
- Follow basic file safety habits
Why File I/O Matters
Programs often need persistence beyond memory. Configuration, logs, exports, and imports all depend on files. C# provides simple static helpers for quick tasks and streaming types for larger workloads.
Writing Text Quickly
The File class covers many one liner scenarios.
string path = "notes.txt";
File.WriteAllText(path, "Hello from C sharp");
string content = File.ReadAllText(path);
Console.WriteLine(content);
WriteAllText creates or overwrites the file. ReadAllText loads the entire file as one string.
Appending lines
File.AppendAllText("log.txt", "Start" + Environment.NewLine);
File.AppendAllText("log.txt", "Finished" + Environment.NewLine);
Append keeps previous content and adds new text at the end.
Writing multiple lines
string[] lines = { "alpha", "beta", "gamma" };
File.WriteAllLines("items.txt", lines);
string[] readBack = File.ReadAllLines("items.txt");
foreach (string line in readBack)
{
Console.WriteLine(line);
}
Streaming with StreamReader
For large files, streaming avoids loading everything at once.
using (StreamReader reader = new StreamReader("items.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
The loop reads one line at a time until the end of the file returns null.
StreamWriter counterpart
using (StreamWriter writer = new StreamWriter("report.txt"))
{
writer.WriteLine("First result");
writer.WriteLine("Second result");
}
The using pattern releases file handles even when an error occurs.
File paths to know
| Expression | Meaning |
|---|---|
| notes.txt | Relative to working directory |
| data/notes.txt | Subfolder relative path |
| Path.Combine | Safe portable path joining |
| Path.GetFullPath | Resolve to an absolute path |
Prefer Path.Combine when joining segments.
string full = Path.Combine("data", "input", "file.txt");
Console.WriteLine(full);
Checking Before You Read
string path = "missing.txt";
if (File.Exists(path))
{
string text = File.ReadAllText(path);
Console.WriteLine(text);
}
else
{
Console.WriteLine("File not found");
}
Exists prevents some failures, but races can still happen. Combine checks with try and catch for robust code.
Handling IO Errors
try
{
string text = File.ReadAllText("config.txt");
Console.WriteLine(text);
}
catch (FileNotFoundException)
{
Console.WriteLine("Config file is missing");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Folder path is wrong");
}
catch (IOException ex)
{
Console.WriteLine("IO problem: " + ex.Message);
}
Specific catches make recovery clearer than one broad handler.
JSON with System.Text.Json
JsonSerializer converts objects to JSON text and back. It is the built in modern choice for .NET apps.
using System.Text.Json;
class User
{
public string Name { get; set; }
public int Age { get; set; }
}
User user = new User { Name = "Asha", Age = 29 };
string json = JsonSerializer.Serialize(user);
Console.WriteLine(json);
User restored = JsonSerializer.Deserialize<User>(json);
Console.WriteLine(restored.Name);
Console.WriteLine(restored.Age);
Reading and writing JSON files
string jsonPath = "user.json";
string payload = JsonSerializer.Serialize(user, new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(jsonPath, payload);
string loaded = File.ReadAllText(jsonPath);
User fromDisk = JsonSerializer.Deserialize<User>(loaded);
Console.WriteLine(fromDisk.Name);
Indented JSON is easier for humans to inspect during learning.
Handling null on deserialize
User maybe = JsonSerializer.Deserialize<User>("{}");
if (maybe is null)
{
Console.WriteLine("Payload was empty");
}
Always consider null when deserializing untrusted or incomplete data.
Common Mistakes
Ignoring exceptions for missing files
A hard crash on the first missing file frustrates users. Provide defaults or clear messages.
Writing without using
Manually opened streams left open can lock files. Prefer using blocks or one shot helpers.
Assuming JSON shape always matches
If properties were renamed, deserialization may produce nulls or throw. Keep models and payloads in sync.
Mixing relative paths across environments
Working directories differ between IDE runs and scheduled jobs. Log the full path when debugging.
Key Takeaways
💡
- File helpers are great for small text tasks; streams fit larger data
- Always release handles with using for open readers and writers
- Check Exists and catch specific IO exceptions for clearer recovery
- System.Text.Json serializes objects to readable JSON and back
- Validate deserialize results before using loaded objects
Practice Questions
- What is the difference between WriteAllText and AppendAllText?
- Why prefer StreamReader for very large files?
- Which exception might File.ReadAllText raise when the file does not exist?
- How do you serialize an object to indented JSON with System.Text.Json?
- Write a small program that saves a name and age to user.json, then reads the file back and prints both values.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions