Example:
variable = new StreamReader( file ).ReadToEnd();
Is that acceptable?
It's good practice to close StreamReader
. Use the following template:
string contents;
using (StreamReader sr = new StreamReader(file))
{
contents = sr.ReadToEnd();
}
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);
You're better off using the using keyword; then you don't need to explicitly close anything.
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);
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();