Reusing a streamreader

  • Thread starter Thread starter Peter
  • Start date Start date
P

Peter

'if you do this
Dim sr As New StreamReader
_(System.AppDomain.CurrentDomain.BaseDirectory& "CR.txt")

' and then loop through values

while sr.peak > -1
......
end while

sr.close

is there a way to reopen the streamreader on the same file?
 
Peter said:
'if you do this

' and then loop through values

while sr.peak > -1
.....
end while

sr.close

is there a way to reopen the streamreader on the same file?

Only,

sr = New StreamReader( AppDomain.CurrentDomain.BaseDirectory & "CR.txt")

When you call Close( ) on the StreamReader, it will have disposed
of it's system resources (i.e., file handle, and this is a _good_ thing).

OTOH, if you hadn't called Close( ) yet, then you could say,

sr.BaseStream.Position = 0

provided System.Diagnostics.Debug.Assert( sr.BaseStream.CanSeek),
which is ordinarily true for FileStreams as in this case; and start reading
over again. In this case, you're always holding onto the file handle, tho.

I'd just re-create the StreamReader. If your concern is remembering
the file directory and name originally used to open the StreamReader,
then save that into a String variable and carry that with you alongside
sr (it's also in CType(sr.BaseStream,System.IO.FileStream).Name
until sr has been closed).


Derek Harmon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top