22. File I/O in C#
Level: Beginner
Goal: Learn how a C# program can save data into files and read data back later.
- What File I/O means
- Write text into a file
- Read text from a file
- Append new text without deleting old text
- Use file paths safely
- Save simple student data
- Handle file errors with try/catch
File I/O means file input and output.
- Input: reading data from a file
- Output: writing data into a file
In a school application, files can store:
- Student list
- Attendance report
- Fee report
- Exam marks
- Error logs
Quick Definitions
- File I/O - Reading and writing data to files
- Path - Location of file on disk
- WriteAllText - Create or replace entire file with text
- ReadAllText - Read entire file as one string
- AppendAllText - Add text to end of file without erasing
- ReadAllLines - Read file as array of lines
- StreamWriter - Efficient class for writing many lines
- StreamReader - Efficient class for reading many lines
- Directory - Folder on disk
- Persistent - Data saved permanently (survives program close)
Why Files Are Needed
Variables store data only while the program is running.
When the program closes, variable data is gone.
Files help us save data permanently.
Example:
Program running -> student data in memory
Program closed -> memory cleared
File saved -> data can be opened again tomorrow
Write Text to a File
Use File.WriteAllText() to create or replace a file.
string path = "student.txt";
string content = "Sahasra Kumar is studying in class 10th";
File.WriteAllText(path, content);
Console.WriteLine("File saved");
If student.txt does not exist, C# creates it.
If it already exists, C# replaces the old content.
Read Text from a File
string path = "student.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);
Append Text to a File
Append means add new content without removing old content.
string path = "students.txt";
File.AppendAllText(path, "Sahasra Kumar\n");
File.AppendAllText(path, "Priya Sharma\n");
Console.WriteLine("Students added");
Read All Lines
If a file has many lines, use ReadAllLines().
string[] students = File.ReadAllLines("students.txt");
foreach (string student in students)
{
Console.WriteLine(student);
}
Check If File Exists
Reading a missing file causes an error.
Check first:
string path = "students.txt";
if (File.Exists(path))
{
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
else
{
Console.WriteLine("File not found");
}
Create a Folder
Use Directory.CreateDirectory().
string folder = "SchoolData";
Directory.CreateDirectory(folder);
Console.WriteLine("Folder is ready");
If the folder already exists, this line does not fail.
Build File Paths Safely
Do not join paths manually like this:
string path = "SchoolData" + "\\" + "students.txt";
Use Path.Combine():
string folder = "SchoolData";
string fileName = "students.txt";
string path = Path.Combine(folder, fileName);
Console.WriteLine(path);
This works better across different operating systems.
Save Student Data as CSV
CSV means comma-separated values.
Example file:
RollNumber,Name,ClassName
STU-001,Sahasra Kumar,10th
STU-002,Priya Sharma,9th
C# example:
var lines = new List<string>();
lines.Add("RollNumber,Name,ClassName");
lines.Add("STU-001,Sahasra Kumar,10th");
lines.Add("STU-002,Priya Sharma,9th");
File.WriteAllLines("students.csv", lines);
Read Student Data from CSV
string[] lines = File.ReadAllLines("students.csv");
foreach (string line in lines.Skip(1))
{
string[] parts = line.Split(',');
string rollNumber = parts[0];
string name = parts[1];
string className = parts[2];
Console.WriteLine($"{rollNumber} - {name} - {className}");
}
Skip(1) skips the header line.
School Management Example
Save and read student names.
Handle File Errors
File operations can fail.
Examples:
- File does not exist
- No permission
- File is open in another program
- Wrong path
Use try-catch.
try
{
string content = File.ReadAllText("students.txt");
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("The file was not found");
}
catch (Exception ex)
{
Console.WriteLine($"File error: {ex.Message}");
}
When You'll Use This in SMS
SMS saves everything to files.
Real file operations:
Student enrollment -> save student.csv
Exam marks added -> append to marks.csv
Attendance marked -> write attendance.txt
Report generated -> save report.pdf
Error occurs -> log error to error.log
Backup created -> copy database to backup/
Import data -> read students.csv, create in DB
Real SMS code:
// Save attendance
string path = Path.Combine("Data", "Attendance", "2024-05-24.txt");
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, attendanceContent);
// Append marks
File.AppendAllText("marks.csv", "101,Mathematics,95\n");
// Read all students
string[] lines = File.ReadAllLines("students.csv");
foreach (string line in lines) { ImportStudent(line); }
// Error logging
File.AppendAllText("error.log", $"{DateTime.Now}: {errorMessage}\n");
Real impact: SMS generates 100+ files daily. Files survive program restart. Database backup requires file operations.
Try This Now
- Create folder structure:
Path.Combine("School", "Data") - Save student list to file
- Append new student without erasing old ones
- Read file back and print each student
- Check if file exists before reading
- Create CSV: "RollNumber,Name,Class"
See how files persist data across program runs.
File I/O explained: WriteAllText, ReadAllText, AppendAllText, ReadAllLines, Path.Combine, StreamWriter/Reader, CSV handling. Video coming soon. Subscribe to NexCoding YouTube for updates.
Common Mistakes
Mistake 1: Reading without checking file exists.
string content = File.ReadAllText("missing.txt");
Better:
if (File.Exists("missing.txt"))
{
string content = File.ReadAllText("missing.txt");
}
Mistake 2: Using WriteAllText() when you wanted to add data.
File.WriteAllText("students.txt", "Sahasra\n");
File.WriteAllText("students.txt", "Priya\n"); // Sahasra is removed
Better:
File.AppendAllText("students.txt", "Priya\n");
Mistake 3: Hardcoding full computer paths.
string path = @"C:\Users\Admin\Desktop\students.txt";
Better:
string path = Path.Combine("SchoolData", "students.txt");
Best Practices
- Use
Path.Combine()for file paths. - Create folders before writing files.
- Check
File.Exists()before reading optional files. - Use
AppendAllText()when adding data. - Use
WriteAllText()only when replacing content is okay. - Use
try-catchfor file operations. - Use CSV for simple export and import practice.
Practice Task
Create a program that:
- Creates a folder called
SchoolData. - Creates a file called
marks.csv. - Writes three student marks.
- Reads the file and prints each student.
Sample CSV:
RollNumber,Name,Marks
STU-001,Sahasra,85
STU-002,Priya,92
STU-003,Arjun,76
Quick Revision
- File I/O means reading and writing files.
WriteAllText()replaces file content.AppendAllText()adds content.ReadAllText()reads full content.ReadAllLines()reads line by line.Path.Combine()builds safe file paths.try-catchhandles file errors.
File I/O means reading data from files and writing data into files.
WriteAllText() replaces the existing file content. AppendAllText() adds new content at the end.
It builds file paths safely and works better across different operating systems.
Because files may be missing, locked, or blocked by permissions. try-catch prevents the program from crashing.
Use ChatGPT, Claude, or Copilot to go deeper on C# File I/O. Try these prompts:
"Explain C# file handling with beginner examples""Give me a student CSV practice task in C#""What is the difference between WriteAllText and AppendAllText?""How do I handle file not found errors in C#?"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.