7

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.

Nuwan
  • 1,226
  • 1
  • 14
  • 38
Alexander Prokofyev
  • 33,874
  • 33
  • 95
  • 118

3 Answers3

12

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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(); }
Scott Saad
  • 17,962
  • 11
  • 63
  • 84
2

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();
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
JSC
  • 3,705
  • 3
  • 26
  • 25
  • 1
    There's no need or point in calling Close as well as Dispose. Just putting it in a using statement is enough. – Jon Skeet Dec 03 '08 at 07:43
  • I agree but the all the developers must know that expensive objects must be closed & disposed if you're not using it anymore. – JSC Dec 03 '08 at 07:49
  • No, they need to be closed *or* disposed. Adding a call to Close like that just adds clutter. Furthermore, if it *were* required, you'd have to put it in a finally block anyway. – Jon Skeet Dec 03 '08 at 08:03
  • Ok you should not close explicitly, but I think you should always(if possible) use the using statement for objects who inherit from IDisposable. Or am I incorrect? – JSC Dec 03 '08 at 08:15
  • No, that's fine - the using statement is good, the call to Close is unnecessary fluff. I'll edit the answer for you. (I can't remember offhand how much rep you need to edit your own answers.) – Jon Skeet Dec 03 '08 at 08:16
  • (I'd also personally not set a value for s, given that it will be overwritten in every situation except where an exception is thrown.) – Jon Skeet Dec 03 '08 at 08:16