Please use File.ReadAllText and the like

Starting from .NET 2.0 the basic file read/write API is finally implemented how it should be. I noticed that some people are still using the old way (StreamReader & Co) so I highly recommend the static methods

  • ReadAllText
  • ReadAllLines
  • ReadAllBytes


  • WriteAllText
  • WriteAllLines
  • WriteAllBytes

on the System.IO.File class.

Thanks :)

Update: I'd like to correct myself. Thanks to kerneltrap (see comments below) I'm not suggesting people should always use File.ReadAll* as opposed to the stream based approach, but this makes a lot of sense for simple and small files you'd normally read in one step, for the code readability reasons.

Of course, if you are doing non-trivial file operations, using using+StreamReader/Writer is better for performance reasons, and you don't have to load the entire file in memory this way. I was just seeing some cases where it was needed to read a small (10 KB) file into a string, and StreamReader.ReadToEnd was used for this purpose. So I'm sorry for not clearly expressing what I actually meant :)

kick it on DotNetKicks.com


kerneltrap said...

What about reading really big files using ReadAllText?

Kirill Osenkov said...

Hi kerneltrap, thanks for your comment. You're absolutely right, I corrected myself in the original post.

Eli Gazit said...

What about the threshold? When should I use ReadAllText vs StreamReader?
It seems that for files larger than 10MB, stream-reader will be better.
I wonder if someone can suggest a detailed method to decided: File.ReadAllText vs StreamReader

Kirill Osenkov said...

This is always a trade-off between performance and simplicity of code.

ReadAllText will keep the entire file in memory, whereas StreamReader gives you flexibility to process the data on the fly, without keeping the whole file in memory. If you care about performance (the code is a bottleneck), measure, measure, measure :)

If you don't care about performance, use whatever appeals to your coding style sense.

My own default threshold is around 1MB in non-critical code. I haven't measured anything though, haven't worked with large files a lot :)


eli said...

I'll do some "Stopwatch" testing... I'll let you know.

Laurent Duveau said...

But ReadAllText is just a wrapper around StreamReader! same code.

Kirill Osenkov said...

Hi Laurent,

it is same code, indeed. But I find that the File.ReadAll* API is much easier to read, write and maintain. Besides, it is considerably shorter and minimizes repetitive code. Finally, it expresses your original intent better - your intent is to read the file, and not to open a stream.

If you have this "gut feeling" about quality code, you'll most probably agree with this.


David Latimer said...

Does the ReadAllText method put a lock on the file?

David Latimer said...

From my investigation, it looks like this method does put a lock on the file.