Fiddling around with it, it seems that StreamReader loads the whole file into
memory on the first read. That's an ... interesting ... design.
Dim strOutput As String = ""
Dim strFilename As String =
My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\FileIODemo.txt"
Using fs As New FileStream(strFilename, FileMode.Create,
FileAccess.Write, FileShare.None)
Using sw As New StreamWriter(fs, System.Text.Encoding.Unicode)
sw.WriteLine("abc")
sw.WriteLine("def")
sw.WriteLine("ghijkl")
sw.WriteLine("mno")
sw.WriteLine("pqrs")
sw.WriteLine("tuvwxyz")
End Using
End Using
Using fs As New FileStream(strFilename, FileMode.Open,
FileAccess.Read, FileShare.None)
Using sr As New StreamReader(fs, System.Text.Encoding.Unicode)
MsgBox("Stream position before first read: " & fs.Position)
strOutput &= sr.ReadLine & vbCrLf
MsgBox("Stream position after first read: " & fs.Position)
strOutput &= sr.ReadLine & vbCrLf
strOutput &= sr.ReadLine & vbCrLf
fs.Seek(0, SeekOrigin.Begin) 'does nothing!!
strOutput &= sr.ReadLine & vbCrLf
strOutput &= sr.ReadLine & vbCrLf
strOutput &= sr.ReadLine & vbCrLf
End Using
End Using
MsgBox(strOutput)
The position after the first read is byte 78 - which is the end of the file.
26 characters = 52 bytes
BOM = 2 bytes
6 CRLFs = 24 bytes
---------------------
TOTAL = 78 bytes
The OP will need to create a new StreamReader, or use a BinaryReader instead.
--
David Streeter
Synchrotech Software
Sydney Australia
[quoted text, click to view] "SurturZ" wrote:
> Strange.
>
> Changing the position of the cursor in the underlying stream doesn't work!
>
> StreamReader must keep its own cursor position or something.
>
> --
> David Streeter
> Synchrotech Software
> Sydney Australia
>
>
> "Family Tree Mike" wrote:
>
> > I think you want to use a FileStream, which supports the Seek() method. You
> > can pass the FileStream to the constructor for the StreamReader if you need
> > methods in the StreamReader.
> >
> > "BobRoyAce" wrote:
> >
> > > I am using an IO.StreamReader to read the contents of a text file. It
> > > all works just fine. However, I do not know of a way to move back to
> > > the beginning of a file. For example, let's say that I read in five
> > > lines from the file, or all of them for that matter. How do I then
> > > point the IO.StreamReader back to the beginning of the file? I would
> > > imagine that I could use "New IO.StreamReader(sFileName)" to create a
> > > new IO.StreamReader pointing to the file, and starting back from the
> > > beginning. I am just wondering if there is another way to do this
> > > (i.e. some method or something).