Need to close FileStream

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • tshad

    Need to close FileStream

    If I have the following:

    fs = new FileStream(xmlF ile, FileMode.Open,
    System.IO.FileA ccess.Read);
    sr = new StreamReader(fs );

    will sr.Close() also close the fs? Or do I need to close both?

    Thanks,

    Tom


  • Ignacio Machin ( .NET/ C# MVP )

    #2
    Re: Need to close FileStream

    On Jul 30, 12:59 pm, "tshad" <ts...@dslextre me.comwrote:
    If I have the following:
    >
                fs = new FileStream(xmlF ile, FileMode.Open,
    System.IO.FileA ccess.Read);
                sr = new StreamReader(fs );
    >
    will sr.Close() also close the fs?  Or do I need to close both?
    >
    Thanks,
    >
    Tom
    Hi,

    Why not using a StreamReader from the start (if it's a Xml use
    XmlReader instead)

    if for some reason you still need to use your code do it like this:
    using( FileStream fs = new FileStream(xmlF ile, FileMode.Open,
    System.IO.FileA ccess.Read) ){
    using( StreamReader sr = new StreamReader(fs ) ){
    }

    }


    It makes sure that the objects are disposed correctly

    Comment

    • Andrew Faust

      #3
      Re: Need to close FileStream

      According to the documentation:

      Implements a TextReader that reads characters from a byte stream in a particular encoding.


      " Close - Closes the StreamReader object and the underlying stream, and
      releases any system resources associated with the reader. (Overrides
      TextReader.Clos e().) "

      Andrew Faust

      "tshad" <tshad@dslextre me.comwrote in message
      news:#pbshWm8IH A.2416@TK2MSFTN GP02.phx.gbl...
      If I have the following:
      >
      fs = new FileStream(xmlF ile, FileMode.Open,
      System.IO.FileA ccess.Read);
      sr = new StreamReader(fs );
      >
      will sr.Close() also close the fs? Or do I need to close both?
      >
      Thanks,
      >
      Tom
      >

      Comment

      • Peter Morris

        #4
        Re: Need to close FileStream

        Much to my annoyance sr.Close will also close the stream.


        Pete

        Comment

        • tshad

          #5
          Re: Need to close FileStream

          So if I am going to read multiple files,

          After the first file, I would do an sr.Close() (which closes fs as well).
          So then I would do another:

          fs = new FileStream(Anot herfile, FileMode.Open,
          System.IO.FileA ccess.Read);

          And another:

          sr = new StreamReader(fs );

          but I never need to do an fs.Close() then.

          Thanks,

          Tom

          "Peter Morris" <mrpmorrisNO@SP AMgmail.comwrot e in message
          news:eZu%23xmm8 IHA.5556@TK2MSF TNGP02.phx.gbl. ..
          Much to my annoyance sr.Close will also close the stream.
          >
          >
          Pete

          Comment

          Working...