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

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

Example:

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

Is that acceptable?

6条回答
  •  遥遥无期
    2020-12-05 13:35

    Yes, whenever you create a disposable object you must dispose of it preferably with a using statement

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

    In this case though you can just use the File.ReadAllText method to simplify the expression

    variable = File.ReadAllText(file);
    

提交回复
热议问题