如果我使用 FileStream 创建 StreamReader,当我关闭 FileStream 时 StreamReader 会关闭还是我需要关闭 StreamReader?
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 提出了关闭最外层包装器的一个很好的观点。关闭最外层流并让它关闭底层流以确保正确释放所有资源是一种很好的做法。
来自反射器...
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);
}
}
}
}
关于c# - 关闭 FileStream 会关闭 StreamReader 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1792191/