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

后端 未结 4 1047
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 03:35

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

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


        
4条回答
  •  失恋的感觉
    2020-12-13 04:24

    If you use ReadToEnd, they are the same. Otherwise, using the StreamReader allows you to read bytes at a time, do some computation with them, and then throw them away as needed. For example, if you had a file containing a list of 2,000 numbers, and you wanted to add them together, you could:

    • Call File.ReadAllText to read everything into a string and then parse through that string to compute the sum.
    • Or you could create a StreamReader and read a few bytes at a time, computing the sum as you go.

    The major difference between these two approaches is the transient memory usage. After you have the sum, you can always throw all the intermediate data away. In the File.ReadAllText approach, at some point you had the entire file contents in memory, while with the StreamReader approach, you only had a few bytes worth of file contents in memory at any one time. This can be an issue depending on the size of your files and the kind of computation you're doing.

    File.ReadAllText is convenient and quick. StreamReader is powerful but more work.

提交回复
热议问题