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
How to open a plain text file in C#?
In C#, you can open and read a plain text file using the StreamReader class from the System.IO namespace. The StreamReader provides methods to read character data from a stream in a particular encoding.
Syntax
Following is the basic syntax for opening a text file with StreamReader −
StreamReader sr = new StreamReader("filepath");
For proper resource management, use the using statement −
using (StreamReader sr = new StreamReader("filepath")) {
// Read file content
}
Using StreamReader to Read Text Files
The most common approach is to use StreamReader with a using statement to ensure the file is properly closed after reading −
using System;
using System.IO;
class Program {
static void Main() {
string filePath = "sample.txt";
// Create a sample file first
File.WriteAllText(filePath, "Hello World!\nThis is line 2.\nThis is line 3.");
try {
using (StreamReader sr = new StreamReader(filePath)) {
string line;
// Read and display lines from the file
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
Console.WriteLine("Error reading file: " + e.Message);
}
}
}
The output of the above code is −
Hello World! This is line 2. This is line 3.
Using File.ReadAllText() Method
For smaller files, you can use the File.ReadAllText() method to read the entire file content at once −
using System;
using System.IO;
class Program {
static void Main() {
string filePath = "sample.txt";
// Create a sample file
File.WriteAllText(filePath, "Hello from C#!\nReading files is easy.\nEnd of file.");
try {
string content = File.ReadAllText(filePath);
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: Hello from C#! Reading files is easy. End of file.
Using File.ReadAllLines() Method
To read all lines into a string array, use File.ReadAllLines() −
using System;
using System.IO;
class Program {
static void Main() {
string filePath = "numbers.txt";
// Create a sample file with numbers
File.WriteAllText(filePath, "Line 1: First\nLine 2: Second\nLine 3: Third\nLine 4: Fourth");
try {
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine("Total lines: " + lines.Length);
for (int i = 0; i
The output of the above code is −
Total lines: 4
Line 1: Line 1: First
Line 2: Line 2: Second
Line 3: Line 3: Third
Line 4: Line 4: Fourth
Comparison of File Reading Methods
| Method | Best For | Memory Usage | Return Type |
|---|---|---|---|
| StreamReader | Large files, line-by-line processing | Low (reads one line at a time) | string (per line) |
| File.ReadAllText() | Small files, entire content needed | High (loads entire file) | string |
| File.ReadAllLines() | Medium files, array of lines needed | High (loads entire file) | string[] |
Error Handling
Always wrap file operations in try-catch blocks to handle common exceptions like FileNotFoundException, DirectoryNotFoundException, and UnauthorizedAccessException −
using System;
using System.IO;
class Program {
static void Main() {
try {
using (StreamReader sr = new StreamReader("nonexistent.txt")) {
Console.WriteLine(sr.ReadToEnd());
}
} catch (FileNotFoundException) {
Console.WriteLine("File not found.");
} catch (DirectoryNotFoundException) {
Console.WriteLine("Directory not found.");
} catch (UnauthorizedAccessException) {
Console.WriteLine("Access denied.");
} catch (Exception e) {
Console.WriteLine("General error: " + e.Message);
}
}
}
The output of the above code is −
File not found.
Conclusion
C# provides multiple ways to read plain text files: StreamReader for line-by-line reading of large files, File.ReadAllText() for reading entire small files, and File.ReadAllLines() for getting an array of lines. Always use proper exception handling and the using statement for resource management.
