How do you check for EOF when using FileStream, Serialization and Binary Files?

Posted on 2004-04-05
Last Modified: 2011-10-03
I'm a Newbie + 1 (I've ask one question already); I want to display all data lines read from a binary file in a multi-line text box.  How do you check for EOF in a DO/LOOP when using FileStream, Serialization and Binary Files? Below is the code that I am attempting to use:

Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
    Dim SerialObj As SalesData
    Dim f As Formatters.Binary.BinaryFormatter
    Dim s As Stream

        SerialObj = New SalesData(Me.txtCustomerName.Text, Me.txtProductDescription.Text, Me.txtQuantity.Text, Me.txtSalesTotal.Text, Me.txtSalesDate.Text)
        f = New Formatters.Binary.BinaryFormatter
        s = New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None)
        SerialObj = f.Deserialize(s)

      'This DO/LOOP does not work.
       Do While s.Seek <> -1
            'Read data lines and display them in a Mulit-Line Text box.
            txtReadLines.Text = SerialObj.fCustomerName & vbCrLf & SerialObj.fProductDescription & vbCrLf & SerialObj.fquantity & vbCrLf & SerialObj.fSalesTotal & vbCrLf & SerialObj.fSalesDate & vbCrLf

        btnRead.Enabled() = False

    Catch ex As Exception
        'Catch Exception Errors
        MsgBox(ex.Message + Chr(13) + Chr(10) + Chr(10) + "File not found.")
    End Try

    'Set focus to the multi-line text box
End Sub
Question by:d2beetle

Expert Comment

ID: 10762431
catch (EndOfStreamException eof) {
            throw new ArgumentException("End of File.", eof);

LVL 28

Expert Comment

ID: 10762569
In Visual Basic .NET you read a text file by first opening a StreamReader on it, and then iterating over all its
 lines until its Peek method returns -1 (which means EOF)

Imports System.IO

Dim sr As New StreamReader("c:\autoexec.bat")

' Display all the text lines in the file.
Do Until sr.Peek = -1
    ' The ReadLine methods reads whole lines.
' Always close a StreamReader when you've done with it.

You can also read one character at a time with using the Read method, or you can read all the remaining
characters withusing the ReadToEnd method. For example, this routine returns the entire contents of any
text file in one operation:
Function ReadTextFile(ByVal filename As String) As String
    Dim sr As New StreamReader(filename)
    ReadTextFile = sr.ReadToEnd()
End Function

Author Comment

ID: 10762902
I have successfully done this using streamreader and streamwriter in previous code working with ASCII text files. My coding attempt this time is to use FileStream for writing object data to binary files; I then want to retrieve that object data and then display it in a multi-line text box. If I remove the DO/LOOP I can successfully display the data for one object line. It looks like this:

jumper cables

This is what I want to see:
phil <data record starts here>

<next record should start here>
<etc ...>

Am I asking the right question(s)?
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

LVL 12

Expert Comment

ID: 10762988
The deserialize method is called once for a supplied file, you don't read through it. The stream is converted in one call -- you don't read through it for each object.  If you want to do that, you can do your own custom file reads, the BinaryFormatter is supposed to save you from that problem.

Here's an example from microsoft, that converts the stream into a hashtable containing three strings.

Sub Deserialize()
        ' Declare the hashtable reference.
        Dim addresses As Hashtable = Nothing

        ' Open the file containing the data that you want to deserialize.
        Dim fs As New FileStream("DataFile.dat", FileMode.Open)
            Dim formatter As New BinaryFormatter

            ' Deserialize the hashtable from the file and
            ' assign the reference to the local variable.
            addresses = DirectCast(formatter.Deserialize(fs), Hashtable)
        Catch e As SerializationException
            Console.WriteLine("Failed to deserialize. Reason: " & e.Message)
        End Try

        ' To prove that the table deserialized correctly,
        ' display the key/value pairs.
        Dim de As DictionaryEntry
        For Each de In addresses
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value)
    End Sub

You can do the same thing for your objects.

Fill a collection or Hashtable with them.  Serialize the hashtable using the BinaryFormatter.Serialize method.

Then reconstruct the hashtable using the DirectCase of the deserialized stream
Dim yourobjects as Hashtable
 yourobjects = DirectCast(formatter.Deserialize(fs), Hashtable)
Then read them out one-by-one

 Dim de As DictionaryEntry
 Dim obj as SalesData
  For Each de In yourobjects
            obj = CType(de.Value, SerialObj)


Author Comment

ID: 10771516

Thanks for your reply, but I beleive that I may be in a little to deep at this point. If I wanted to do what you suggest and create my own file reads, how would I go about doing it or should I just swim for the shore now?
LVL 12

Accepted Solution

dfiala13 earned 250 total points
ID: 10771541
I think it's pretty straightforward.  Here's the link from the MS Site on how it works.

Just start small.  Serialize a single object and deserialize it.  Use the microsoft code as a starting point.  Add an object when you feel comfortable.  Once you figure out the second one, the rest will be easy.  I think the secret is to use collection classes (collections, hashtables) when you have multiple instances of the same type of object.

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK ( for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question