[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3691
  • Last Modified:

reset a streamreader to the beginning?


Hey, I am using a System.IO.StreamReader, specifically the ReadLine method to parse through an ascii file and extract the data I need.  I am using this because I used to use the old line input command a lot (actually have used it for about 15 years so this a weird shift).  Anyway, the ReadLine method, called successively, reads successive lines of the file.  Is there a way to reset this to the beginning, so that the next ReadLine method reads the first line, without closing and reinstantiating the reader?

Thanks.
0
riceman0
Asked:
riceman0
  • 2
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Yes...like this:

        Dim sr As New System.IO.StreamReader("c:\somefile.txt")
        Dim line As String

        Debug.WriteLine("Contents:")
        line = sr.ReadLine
        While Not IsNothing(line)
            Debug.WriteLine(line)
            line = sr.ReadLine
        End While

        sr.DiscardBufferedData()
        sr.BaseStream.Seek(0, IO.SeekOrigin.Begin)

        Debug.WriteLine("Contents Again:")
        line = sr.ReadLine
        While Not IsNothing(line)
            Debug.WriteLine(line)
            line = sr.ReadLine
        End While

        sr.Close()
0
 
riceman0Author Commented:

Thanks.  Question: I guess that means that the StreamReader contains a BaseStream object, rather than derives from the BaseStream class (in which case the basestream methods would just appear as streamreader methods, right?).  Any idea why they did it that way?  (As you might remember I'm just getting the hang of .NET framework...)
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
That's a good question...

I think they did it that way so they could control how the underlying stream is accessed via a StreamReader.  This makes it ~easier~ to use for the end user because it is harder to screw up the way the file is read since you only have a limited way in which you can access the file stream.

They provided other classes to access file streams in different ways or at lower levels.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now