2020年10月12日 星期一

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?

47

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

沒有留言:

張貼留言