FileStream Read from and Write to a Text File (VB)

G

Guest

I've already figured out how to read from a Structured text file using the
StreamReader, and I've also figured out how to Search for a specific Line
within the File (StreamReader.ReadLine). I've also figured out how to
programatically make some changes to that line using String Operations.

Now I want to "Write" those changes back to the file without changing the
current structure. In otherwords I want to be able to Find and Replace. All
the examples show how to Read or Write to Text Files but they don't show you
how to:

* Read From
* Make Changes
* Write Back to
 
D

David Browne

GeoWizz said:
I've already figured out how to read from a Structured text file using the
StreamReader, and I've also figured out how to Search for a specific Line
within the File (StreamReader.ReadLine). I've also figured out how to
programatically make some changes to that line using String Operations.

Now I want to "Write" those changes back to the file without changing the
current structure. In otherwords I want to be able to Find and Replace.
All
the examples show how to Read or Write to Text Files but they don't show
you
how to:

* Read From
* Make Changes
* Write Back to
--
The StreamReader is just that, a reader. There is also a StreamWriter,
which makes writing easier. Both of these sit on top of a System.IO.Stream,
and in your case it's a System.IO.FileStream. But these types provide a
string-oriented read-only or write-only view of the file. It's tricky to
use a StreamReader and simultaneously write to the file since the
StreamReader keeps an internal read-ahead buffer to find the ends of lines,
and so the underlying stream's position is ahead of the line you are
reading.

To read and write, you should go down a level and use the FileStream
directly. The FileStream has methods to read and write bytes from a file.
You are on you own for finding the ends of lines and for decoding the bytes
into strings (see System.Text.Encoding).

Alternatively if the file is small, you can use a StreamReader and a
StreamWriter writing a new output file and then switch the files when you're
done.

David
 

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

Top