Problems using Seek with Filestream

Lindsay

New member
Joined
Feb 9, 2009
Messages
4
Programming Experience
5-10
I am trying to read in a file and store the byte position of each line read so that I can write out to another file the records in any order that I want. I am doing more manipulation of the lines, hence why I need the line position from the original file, but for simplicity sake, I am just including code to display the problem I am encountering. When I read in the file, I am getting the correct file position, but when I write out the lines, every 1024 characters it is re-writing whatever current line it is on. I am assume there is some buffer that is coming into play that I am not familiar with, so any help or advice would be appreciated.

VB.NET:
Dim srReader As StreamReader
Dim LongString As String
Dim fsReader As FileStream
Dim fsWriter As FileStream
Dim srWriter As StreamWriter
Dim LinePointer As Long
Dim IndexArray As New ArrayList

OpenFileDialog1.ShowDialog()

fsReader = New FileStream(OpenFileDialog1.FileName, FileMode.Open)
srReader = New StreamReader(fsReader)

fsWriter = New FileStream(OpenFileDialog1.FileName & ".Wrote", FileMode.Create)
srWriter = New StreamWriter(fsWriter)

'Read in each line and store the byte position for the start of each line
LinePointer = 0
Do
    LongString = srReader.ReadLine
    IndexArray.Add(LinePointer)
    LinePointer += Len(LongString + Environment.NewLine)
Loop Until srReader.Peek = -1

'Seek to the byte position and read in a line from that point
For x As Long = 0 To IndexArray.Count - 1
    fsReader.Seek(IndexArray(x), SeekOrigin.Begin)

    LongString = srReader.ReadLine

    srWriter.WriteLine(LongString)
Next

srReader.Close()
srWriter.Close()
fsReader.Close()
fsWriter.Close()
 
from help:
StreamReader might buffer input such that the position of the underlying stream will not match the StreamReader position.
 
Ya, I saw that too, and if you were to use FileStream.Position after doing a readline it would show the position as being at 1024, even if the line you read in was only 100 chars. I wasn't sure if that applied to when you were seeking to an exact position within a file.
It almost seems like when you do a seek, it goes to that position within the buffer and if it doesn't encounter a newline character, it then goes to that exact same position in file (ie the start of the line) and appends the line to what was read from the buffer. Needless to say this is not what I expected it to do.
 
As is the case, continue searching and you can usually find the solution. Using
srReader.DiscardBufferedData()
before you call the seek method looks like it works. It clears and reloads the buffer based on the sek position.
 
Back
Top