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.

    原文链接

  • 相关阅读:
    几个工具类
    C#学习-程序集和反射
    Unity学习-鼠标的常用操作(八)
    Unity学习-碰撞检测(七)
    Unity学习-摄像机的使用(六)
    Unity学习-地形的设置(五)
    Unity学习-预制(四)
    Unity学习-元素类型(三)
    Unity学习-软件的基本操作(二)
    Unity学习-工具准备(一)
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/12299038.html
Copyright © 2011-2022 走看看