开发者

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

Example:

variable = new StreamReader( file ).Re开发者_如何转开发adToEnd();

Is that acceptable?


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


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


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


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


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

string contents;

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜