Closing StreamReader after ReadToEnd

Is it possible somehow to close StreamReader after calling ReadToEnd method in construction like this:

string s = new StreamReader("filename", Encoding.UTF8).ReadToEnd();

Any alternative elegant construction with the same semantics will be also accepted.

Answers


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.

If you don't specify the encoding, it will use UTF-8 automatically.


You could use a using statement, which automatically closes the stream:

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

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

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

Need Your Help

jquery ajax cache false but issues with ie bassed browser

jquery ajax internet-explorer browser-cache

below code works perfect on firefox and chrome however getting strange issues with ie.

voluptuous: how to validate non-string value from json data in HTTP POST

python json http post voluptuous

I'm implementing some REST API with flask. In one of the APIs, I need to submit a location defined by longitude and latitude. So naturally I'm doing this with httpie: