c# - 关闭 FileStream 会关闭 StreamReader 吗?

标签 c# .net-3.5 filestream streamreader

如果我使用 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/

相关文章:

c# - SQLDataReader 返回带有附加分隔符的字符串\\\\

c# - 我拔下客户端工作站的插头,长时间运行的数据库进程会发生什么情况?

vb.net - 在运行时更改 API 引用 VB.NET 3.5

c - 为什么 rewind() 在这个简单的程序中没有按预期工作?

sql - 处理 SQL FILESTREAM 数据损坏和备份

C# 没有像我告诉的那样处理控件

c# - IList<T> 似乎不包含方法 "Remove"

c# - 创建一个没有文件的文件流 C#

c# - 如何使用 ASP.Net 将 Mysql 表值导出到现有的 Excel 工作表模板

.net - 如何用所需字符填充字符串