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

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

Example:

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

Is that acceptable?

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 13:30

    It's good practice to close StreamReader. Use the following template:

    string contents;
    
    using (StreamReader sr = new StreamReader(file)) 
    {
       contents = sr.ReadToEnd();
    }
    

提交回复
热议问题