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

Matt Ralston picture Matt Ralston · Nov 9, 2010 · Viewed 48.1k times · Source

Example:

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

Is that acceptable?

Answer

badbod99 picture badbod99 · Nov 9, 2010

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");