Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Different ways of Reading a file in C#
There are several ways to read files in C#, each suited for different scenarios. C# provides various classes in the System.IO namespace for file operations, including reading text files, binary files, and handling different data types efficiently.
Using StreamReader for Text Files
The StreamReader class is the most common way to read text files line by line. It provides efficient reading with proper resource management using the using statement −
using System;
using System.IO;
class Program {
static void Main(string[] args) {
// Create a sample file first
File.WriteAllText("sample.txt", "Line 1\nLine 2\nLine 3\nHello World!");
try {
using (StreamReader sr = new StreamReader("sample.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
The output of the above code is −
Line 1 Line 2 Line 3 Hello World!
Using File.ReadAllText() Method
For smaller files, you can read the entire content at once using the File.ReadAllText() method −
using System;
using System.IO;
class Program {
static void Main(string[] args) {
// Create a sample file
File.WriteAllText("content.txt", "This is the complete file content.\nSecond line here.");
try {
string content = File.ReadAllText("content.txt");
Console.WriteLine("File Content:");
Console.WriteLine(content);
} catch (Exception e) {
Console.WriteLine("Error reading file: " + e.Message);
}
}
}
The output of the above code is −
File Content: This is the complete file content. Second line here.
Using File.ReadAllLines() Method
To read all lines into a string array, use the File.ReadAllLines() method −
using System;
using System.IO;
class Program {
static void Main(string[] args) {
// Create a sample file
File.WriteAllLines("lines.txt", new string[] {"First line", "Second line", "Third line"});
try {
string[] lines = File.ReadAllLines("lines.txt");
Console.WriteLine("Total lines: " + lines.Length);
for (int i = 0; i < lines.Length; i++) {
Console.WriteLine($"Line {i + 1}: {lines[i]}");
}
} catch (Exception e) {
Console.WriteLine("Error reading file: " + e.Message);
}
}
}
The output of the above code is −
Total lines: 3 Line 1: First line Line 2: Second line Line 3: Third line
Using BinaryReader for Binary Files
For binary files containing structured data, use BinaryReader to read specific data types −
using System;
using System.IO;
class Program {
static void Main(string[] args) {
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3.14157;
bool b = true;
string s = "I am happy";
// Create and write to the binary file
try {
bw = new BinaryWriter(new FileStream("mydata", FileMode.Create));
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
bw.Close();
} catch (IOException e) {
Console.WriteLine(e.Message + "<br> Cannot create or write to file.");
return;
}
// Read from the binary file
try {
br = new BinaryReader(new FileStream("mydata", FileMode.Open));
i = br.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = br.ReadDouble();
Console.WriteLine("Double data: {0}", d);
b = br.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
s = br.ReadString();
Console.WriteLine("String data: {0}", s);
br.Close();
} catch (IOException e) {
Console.WriteLine(e.Message + "<br> Cannot read from file.");
}
}
}
The output of the above code is −
Integer data: 25 Double data: 3.14157 Boolean data: True String data: I am happy
Comparison of File Reading Methods
| Method | Best For | Memory Usage |
|---|---|---|
| StreamReader | Large text files, line-by-line processing | Low (reads incrementally) |
| File.ReadAllText() | Small text files, simple reading | High (loads entire file) |
| File.ReadAllLines() | Text files where you need all lines as array | High (loads entire file) |
| BinaryReader | Binary files with structured data | Low (reads specific data types) |
Conclusion
C# offers multiple approaches for reading files: StreamReader for efficient line-by-line text reading, File.ReadAllText() and File.ReadAllLines() for simple text file operations, and BinaryReader for structured binary data. Choose the method based on file size, data type, and memory constraints.
