如果我使用FileStream创建StreamReader,当我关闭FileStream时StreamReader会关闭还是我还需要关闭StreamReader?
@H_301_2@public void ReadFile()
{
var file = new FileStream("c:\file.txt",FileMode.Open,FileAccess.Read);
var reader = new StreamReader(file);
try
{
txtFile.Text = reader.ReadToEnd();
}
catch (Exception)
{
throw;
}
finally
{
file.Close();
}
}
解决方法
基本上是的.您实际上不必关闭StreamReader.如果这样做,它所做的就是关闭底层流.
@Bruno对关闭最外层包装器提出了一个很好的观点.最好关闭最外层的流并让它关闭底层流,以确保正确释放所有资源.
来自Reflector ……
@H_301_2@public class StreamReader : TextReader { public override void Close() { this.Dispose(true); } protected override void Dispose(bool disposing) { try { if ((this.Closable && disposing) && (this.stream != null)) { this.stream.Close(); } } finally { if (this.Closable && (this.stream != null)) { this.stream = null; this.encoding = null; this.decoder = null; this.byteBuffer = null; this.charBuffer = null; this.charPos = 0; this.charLen = 0; base.Dispose(disposing); } } } }