Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing StreamReader after ReadToEnd

Tags:

c#

.net

file-io

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.

like image 755
Alexander Prokofyev Avatar asked Dec 03 '08 07:12

Alexander Prokofyev


People also ask

Do you need to close a StreamReader?

1 Answer. No, there is no need to explicitly call reader. Close if the reading process is inside a using block. By using a using statement (that sounds awkward out loud) everything will be closed and disposed when the code exits the block.

Does ReadToEnd close the stream?

ReadToEnd assumes that the stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided.

What is StreamReader and StreamWriter in C#?

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.


1 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.

like image 106
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet