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

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

Example:

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

Is that acceptable?

6条回答
  •  粉色の甜心
    2020-12-05 13:42

    You need to Dispose of objects that implement IDisposable. Use a using statement to make sure it gets disposed without explicitly calling the Dispose method.

    using (var reader = new StreamReader(file))
    {
      variable = reader.ReadToEnd();
    }
    

    Alternately, use File.ReadAllText(String)

    variable = File.ReadAllText(file);
    

提交回复
热议问题