C# 在 ReadToEnd 后关闭 StreamReader
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/336414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closing StreamReader after ReadToEnd
提问by Alexander Prokofyev
Is it possible somehow to close StreamReader after calling ReadToEnd method in construction like this:
在构造中调用 ReadToEnd 方法后,是否有可能以某种方式关闭 StreamReader,如下所示:
string s = new StreamReader("filename", Encoding.UTF8).ReadToEnd();
Any alternative elegant construction with the same semantics will be also accepted.
任何具有相同语义的替代优雅构造也将被接受。
采纳答案by Jon Skeet
I think the method you're really after is File.ReadAllText, if you're just trying to read all the text from a file in the shortest possible code.
我认为您真正想要的方法是File.ReadAllText,如果您只是想以尽可能短的代码读取文件中的所有文本。
If you don't specify the encoding, it will use UTF-8 automatically.
如果不指定编码,它将自动使用 UTF-8。
回答by Scott Saad
回答by JSC
No there isn't but it's always a good practice to use dispose objects who inherit form IDisposable. If you don't do this in a loop you will get memory leaks
不,没有,但使用继承 IDisposable 形式的处置对象始终是一个好习惯。如果您不在循环中执行此操作,则会出现内存泄漏
string s = string.Empty;
using(StreamReader sr = new StreamReader("filename", Encoding.UTF8))
{
s = sr.ReadToEnd();
}