Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to explicitly close the StreamReader in C# when using it to load a file into a string variable?

Example:

variable = new StreamReader( file ).ReadToEnd(); 

Is that acceptable?

like image 916
Matt Ralston Avatar asked Nov 09 '10 17:11

Matt Ralston


People also ask

What is SR close ()?

Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

What does StreamReader return?

StreamReader. ReadLine() method reads a line of characters from the current stream and returns the data as a string.

What is StreamReader function?

A StreamReader is a TextReader which means it is a Stream wrapper. A TextReader will convert (or encode) Text data (string or char) to byte[] and write them down to the underlying Stream .


1 Answers

No, this will not close the StreamReader. You need to close it. Using does this for you (and disposes it so it's GC'd sooner):

using (StreamReader r = new StreamReader("file.txt")) {   allFileText = r.ReadToEnd(); } 

Or alternatively in .Net 2 you can use the new File. static members, then you don't need to close anything:

variable = File.ReadAllText("file.txt"); 
like image 157
badbod99 Avatar answered Oct 04 '22 09:10

badbod99