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

孤街浪徒 提交于 2019-12-17 15:53:28

问题


Example:

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

Is that acceptable?


回答1:


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



回答2:


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



回答3:


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



回答4:


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



回答5:


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

string contents;

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



回答6:


You're better off using the using keyword; then you don't need to explicitly close anything.



来源:https://stackoverflow.com/questions/4136490/do-i-need-to-explicitly-close-the-streamreader-in-c-sharp-when-using-it-to-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!