Reading Files in C# – Learn How to Read Files Easily!
Hey there, coder! 👋 Ever wondered how to read files in C#? Whether you’re fetching user data, loading configuration settings, or processing logs, reading files is super important.
📂 Introduction – Why Read Files?
Imagine you are working on a task manager app. You save user tasks in a file, and now you need to display them back whenever the user logs in. How do you get that data? You read the file!
Reading files in C# is super easy, and there are multiple ways to do it. Let’s explore them one by one! 🧐
📚 What You Are Going to Learn in This Lesson
✔️ Different ways to read files in C#
✔️ Simple and effective methods for reading file content
✔️ Real-world examples with complete code and output
📌 Method 1: Using File.ReadAllText()
The simplest way to read an entire file is by using File.ReadAllText(). It reads the entire content as a string.
📌 Example 1: Reading an Entire File
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Writing some text to the file first
File.WriteAllText(filePath, "Hello, this is a test file!");
// Reading the file
string content = File.ReadAllText(filePath);
Console.WriteLine("File Content: " + content);
}
}
🖥️ Output:
File Content: Hello, this is a test file!
📌 Explanation:
1️⃣ The program writes “Hello, this is a test file!” to a file.
2️⃣ File.ReadAllText(filePath) reads the file and stores it in a string.
3️⃣ The content is then displayed on the console.
Simple, right? 😃
📌 Method 2: Using File.ReadAllLines()
If you want to read a file line by line, use File.ReadAllLines(). It returns an array of strings, where each element is a line from the file.
📌 Example 2: Reading a File Line by Line
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Writing multiple lines to the file
File.WriteAllLines(filePath, new string[] { "Line 1", "Line 2", "Line 3" });
// Reading file line by line
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine("File Content:");
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}
🖥️ Output:
File Content:
Line 1
Line 2
Line 3
📌 Explanation:
1️⃣ The program writes three lines to a file.
2️⃣ File.ReadAllLines(filePath) reads the file and stores each line in an array.
3️⃣ We then loop through the array and print each line.
This method is great when you need to process each line separately.
📌 Method 3: Using StreamReader (Best for Large Files)
StreamReader is useful when you need to read large files efficiently without loading everything into memory at once.
📌 Example 3: Reading a File Using StreamReader
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Writing some text to the file
File.WriteAllText(filePath, "Line A\nLine B\nLine C");
// Reading file using StreamReader
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
🖥️ Output:
Line A
Line B
Line C
📌 Explanation:
1️⃣ StreamReader reads the file line by line without loading the entire file into memory.
2️⃣ The while loop continues reading until there are no more lines.
3️⃣ It prints each line one by one.
This method is best for large files where loading everything at once isn’t practical.
🌍 Real-World Scenario: Loading a Configuration File
Imagine you’re developing a game, and you need to load game settings stored in a file. Here’s how you can read settings using C#:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "config.txt";
// Writing config settings
File.WriteAllLines(filePath, new string[] { "Volume=80", "Resolution=1920x1080", "Fullscreen=True" });
Console.WriteLine("Game Settings:");
// Reading settings from file
foreach (string setting in File.ReadAllLines(filePath))
{
Console.WriteLine(setting);
}
}
}
🖥️ Output:
Game Settings:
Volume=80
Resolution=1920x1080
Fullscreen=True
This is how real-world applications store and read configuration settings from a file. 🚀
Conclusion
Great job! 🎉 You now know how to read files in C# using different methods like File.ReadAllText(), File.ReadAllLines(), and StreamReader.
Remember:
✔️ Use File.ReadAllText() for small files.
✔️ Use File.ReadAllLines() when you need line-by-line processing.
✔️ Use StreamReader for large files to avoid memory issues.
Now, try reading different types of files on your own. If you get stuck, don’t worry—I’m here to help! 😃
Next What?
Awesome! You just mastered reading files in C#. But what if you want to delete or move files? No worries! In the next chapter, you’ll learn how to delete and move files in C# easily.
So, stay tuned and keep coding! 🚀
