tags:

views:

706

answers:

3

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.

Thanks!

+1  A: 

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
I do it this way now, but hope what there is a shorter solution without explicit declaration of StreamReader variable.
Alexander Prokofyev
@jon-skeet's answer is the way to go
Scott Saad
A: 

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();
}
JSC
There's no need or point in calling Close as well as Dispose. Just putting it in a using statement is enough.
Jon Skeet
JSC
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
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
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
(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
+10  A: 

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
Great! Thank you!
Alexander Prokofyev