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

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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
 
Back
Top