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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:43:45  来源:igfitidea点击:

Closing StreamReader after ReadToEnd

c#.netfile-io

提问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

You could use a usingstatement, which automaticallycloses the stream:

您可以使用using语句,它会自动关闭流:

string s = null;    
using ( StreamReader reader = new StreamReader( "filename", Encoding.UTF8 ) { s = reader.ReadToEnd(); }

回答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();
}