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# - 如何在 C# Windows 8.1 Store App 中翻转和旋转图像

c# - FileHelpers:混合分隔和固定长度记录

c# - 如何使用命令行+参数注册.Net 服务?

c# - C#访问路径被拒绝错误

java - 如何使用 JAX-RS 从我的 Java 服务器端返回一个 Zip 文件?

c# - 如何将 GetStringAsync 结果反序列化为翻译文本

c# - 如何在 Visual Studio 中为 Windows 计算机上的 Xamarin 应用程序设计用户界面?

wpf - 只读在 WPF RichTextBox 中运行元素?

c# - 在 ASP.Net 的 GridView 中获取 "checked"复选框的 rowID 值

c# - 异步 FileStream 读取的正确结构