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

后端 未结 6 666
予麋鹿
予麋鹿 2020-12-05 12:53

Example:

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

Is that acceptable?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 13:50

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

提交回复
热议问题