File.ReadAllText()和之间的差额,使用一个StreamReader读取文件内容是什么? [英] Any difference between File.ReadAllText() and using a StreamReader to read file contents?

查看:827
本文介绍了File.ReadAllText()和之间的差额,使用一个StreamReader读取文件内容是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

起初,我用了一个的StreamReader 来从文件中读取文本:

  StreamReader的读者=新的StreamReader(dialog.OpenFile()); 
txtEditor.Text = reader.ReadToEnd();



但发现了 File.ReadAllText 这似乎简化了我的代码,以1行。有没有两者之间的任何差别? ?什么时候应该使用一个比其他

  txtEditor.Text = File.ReadAllText(dialog.FileName); 


解决方案

有没有区别,如果你使用的是 ReadToEnd的()方法。所不同的是,如果你使用的是大型文件的的ReadLine()方法,你不加载整个文件到内存中,而是让你对它进行处理块。



因此​​,使用 File.ReadAllText()而不是 ReadToEnd的(),因为它使你的代码更短,更易读。它也需要正确处理资源的照顾,你可能会忘记用的StreamReader (如你在你的代码片段一样)。


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);

解决方案

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).

这篇关于File.ReadAllText()和之间的差额,使用一个StreamReader读取文件内容是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆