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

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

Example:

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

Is that acceptable?

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 13:50

    You should always dispose of your resources.

    // the using statement automatically disposes the streamreader because
    // it implements the IDisposable interface
    using( var reader = new StreamReader(file) )
    {
        variable = reader.ReadToEnd();
    }
    

    Or at least calling it manually:

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

提交回复
热议问题