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
C# Program to read all the lines of a file at once
The File.ReadAllText() method in C# reads all the text from a file and returns it as a single string. This method is part of the System.IO namespace and provides a simple way to read entire file contents at once.
When you need to read all lines from a text file in one operation, ReadAllText() is more efficient than reading line by line, especially for smaller files.
Syntax
Following is the syntax for the File.ReadAllText() method −
public static string ReadAllText(string path);
Parameters
- path − The file path to read from. Can be relative or absolute path.
Return Value
Returns a string containing all the text in the file, including newline characters between lines.
Using File.ReadAllText() Method
Let's say we have a file "hello.txt" with the following content −
One Two Three
Example
using System;
using System.IO;
public class Demo {
public static void Main() {
string myPath = "hello.txt";
string allLines;
// Create the file first for demonstration
File.WriteAllText(myPath, "One\nTwo\nThree");
// Read all text from the file
allLines = File.ReadAllText(myPath);
Console.WriteLine("File contents:");
Console.WriteLine(allLines);
// Clean up
File.Delete(myPath);
}
}
The output of the above code is −
File contents: One Two Three
Using File.ReadAllLines() for Line Array
If you need each line as a separate array element, use File.ReadAllLines() instead −
Example
using System;
using System.IO;
public class Demo {
public static void Main() {
string myPath = "data.txt";
// Create file with sample data
File.WriteAllText(myPath, "Line 1\nLine 2\nLine 3\nLine 4");
// Read all lines into string array
string[] lines = File.ReadAllLines(myPath);
Console.WriteLine("Total lines: " + lines.Length);
for (int i = 0; i < lines.Length; i++) {
Console.WriteLine($"Line {i + 1}: {lines[i]}");
}
// Clean up
File.Delete(myPath);
}
}
The output of the above code is −
Total lines: 4 Line 1: Line 1 Line 2: Line 2 Line 3: Line 3 Line 4: Line 4
Comparison of File Reading Methods
| Method | Return Type | Use Case |
|---|---|---|
| File.ReadAllText() | string | Read entire file as single string |
| File.ReadAllLines() | string[] | Read file as array of lines |
| StreamReader | Line by line | Read large files efficiently |
Conclusion
The File.ReadAllText() method provides a simple way to read entire file contents as a single string. For processing individual lines, use File.ReadAllLines() to get an array of strings instead.
