Reading Files using File Methods
There are two additional methods of reading files which are significantly shorter in terms of syntax.
Consider a file called "text.txt" which has the following content:
text.txt
123First Second Third
File.ReadAllText Method
We can use the File.ReadAllText
to retrieve all the text from a file at once:
index.cs
12string text = File.ReadAllText("C:/Users/Admin/Desktop/text.txt"); Console.WriteLine(text);
Output:
First
Second
Third
File.ReadAllLines Method
The File.ReadAllLines
method retrieves all text as well, however it returns data in the form of a string
array where each element is an individual line from the file:
index.cs
12345string[] lines = File.ReadAllLines("C:/Users/Admin/Desktop/text.txt"); foreach(string line in lines) { Console.WriteLine(line); }
Output:
First
Second
Third
The difference between StreamReader and the File methods is that with StreamReader we have more control over how many lines and which lines we want to read from the file. For-example if there's a file with over a million lines and we want to retrieve only the first 1000 lines or some specific lines from the middle of the file then in that case using StreamReader will be much more efficient.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 2.04
Reading Files using File Methods
Scorri per mostrare il menu
There are two additional methods of reading files which are significantly shorter in terms of syntax.
Consider a file called "text.txt" which has the following content:
text.txt
123First Second Third
File.ReadAllText Method
We can use the File.ReadAllText
to retrieve all the text from a file at once:
index.cs
12string text = File.ReadAllText("C:/Users/Admin/Desktop/text.txt"); Console.WriteLine(text);
Output:
First
Second
Third
File.ReadAllLines Method
The File.ReadAllLines
method retrieves all text as well, however it returns data in the form of a string
array where each element is an individual line from the file:
index.cs
12345string[] lines = File.ReadAllLines("C:/Users/Admin/Desktop/text.txt"); foreach(string line in lines) { Console.WriteLine(line); }
Output:
First
Second
Third
The difference between StreamReader and the File methods is that with StreamReader we have more control over how many lines and which lines we want to read from the file. For-example if there's a file with over a million lines and we want to retrieve only the first 1000 lines or some specific lines from the middle of the file then in that case using StreamReader will be much more efficient.
Grazie per i tuoi commenti!