Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between File.ReadAllText() and using a StreamReader to read file contents?

Tags:

c#

At first I used a StreamReader to read text from a file:

StreamReader reader = new StreamReader(dialog.OpenFile()); txtEditor.Text = reader.ReadToEnd(); 

but found out about File.ReadAllText which seems to simplify my code to 1 line. Are there are any differences between the two? When should I use one over the other?

txtEditor.Text = File.ReadAllText(dialog.FileName); 
like image 893
Jiew Meng Avatar asked Aug 23 '10 07:08

Jiew Meng


People also ask

What is file ReadAllText?

ReadAllText(String) Opens a text file, reads all the text in the file, and then closes the file. ReadAllText(String, Encoding) Opens a file, reads all text in the file with the specified encoding, and then closes the file.

What is the difference between ReadAllLines and ReadAllText in C#?

ReadAllLines returns an array of strings. Each string contains a single line of the file. ReadAllText returns a single string containing all the lines of the file.

Which method of FileStream class is use for reading line from file?

The ReadLine method of the StreamReader reads a line of characters from the current stream and returns the data as a string. The code example reads a file line by line.


1 Answers

There are no differences if you are using the ReadToEnd() method. The difference is if you are using the ReadLine() method for large files as you are not loading the whole file into memory but rather allows you to process it in chunks.

So use File.ReadAllText() instead of ReadToEnd() as it makes your code shorter and more readable. It also takes care of properly disposing resources as you might forget doing with a StreamReader (as you did in your snippet).

like image 148
Darin Dimitrov Avatar answered Sep 19 '22 15:09

Darin Dimitrov