zoukankan      html  css  js  c++  java
  • Does disposing StreamReader or StreamWriter close the stream?(转载)


    I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by using or just when it is not referenced, is the stream closed as well??
    I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed.


    Yes, StreamReader, StreamWriter, BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don't dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a using statement. (In fact, none of these classes have finalizers, nor should they have.)
    Personally I prefer to have a using statement for the stream as well. You can nest using statements without braces quite neatly:

    using (Stream stream = ...)
    using (StreamReader reader = new StreamReader(stream, Encoding.Whatever))
    {
    }

    Even though the using statement for the stream is somewhat redundant (unless the StreamReader constructor throws an exception) I consider it best practice as then if you get rid of the StreamReader and just use the stream directly at a later date, you'll already have the right disposal semantics.

    原文链接

  • 相关阅读:
    快速排序
    开博寄语
    002易语言编写获取人物坐标
    001寻找人物的坐标
    借条范例:
    python3练习-装饰器
    python3练习-杨辉三角/帕斯卡三角形
    python3内置函数
    Tableau修改参考线上显示的标签
    Tableau10.0学习随记-分组问题
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/12299038.html
Copyright © 2011-2022 走看看