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.

    原文链接

  • 相关阅读:
    64位windows 7下配置TortoiseGit(转)
    linux中fork函数详解(转)
    Socket通信的Python实现
    Socket
    浅谈CSRF攻击方式(转)
    Burpsuite常用模块详解以及渗透测试上的运用
    大佬内网渗透技巧的独白(思路篇)
    CTFcrackTools-V3
    厂商要知道的漏洞防护措施
    如何运用kali-xplico网络取证分析?点开看看吧
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/12299038.html
Copyright © 2011-2022 走看看