Working with Files
Part of the Logic & Flow section of Coddy's C# journey — lesson 26 of 66.
In C#, you can work with files using classes from the System.IO namespace. The two main classes for text files are StreamReader (for reading) and StreamWriter (for writing).
Writing to a file:
using System.IO;
// Create a StreamWriter to write to a file
StreamWriter writer = new StreamWriter("myfile.txt");
// Write text to the file
writer.WriteLine("Hello, World!");
writer.WriteLine("This is line 2");
// Close the file
writer.Close();Reading from a file:
using System.IO;
// Create a StreamReader to read from a file
StreamReader reader = new StreamReader("myfile.txt");
// Read all content from the file
string content = reader.ReadToEnd();
Console.WriteLine(content);
// Close the file
reader.Close();Reading line by line:
StreamReader reader = new StreamReader("myfile.txt");
// Read first line
string line1 = reader.ReadLine();
Console.WriteLine(line1);
// Read second line
string line2 = reader.ReadLine();
Console.WriteLine(line2);
reader.Close();Remember to always close your files with Close() when you're done!
Challenge
EasyCreate a method named ReadFile that:
- Takes one string parameter:
filename - Reads the content from the file using
StreamReader - Prints the content to the console
- Closes the reader
Cheat sheet
Work with files using the System.IO namespace. Use StreamWriter to write and StreamReader to read.
Writing to a file:
StreamWriter writer = new StreamWriter("myfile.txt");
writer.WriteLine("Hello, World!");
writer.Close();Reading from a file:
StreamReader reader = new StreamReader("myfile.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
reader.Close();Reading line by line:
StreamReader reader = new StreamReader("myfile.txt");
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();Key methods:
WriteLine(text)- Write a line to the fileReadToEnd()- Read all text from the fileReadLine()- Read one line from the fileClose()- Close the file (always do this!)
Try it yourself
using System;
using System.IO;
class Program
{
public static void ReadFile(string filename)
{
// Write your code here
}
static void Main(string[] args)
{
string filename = Console.ReadLine();
ReadFile(filename);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety