Now before we start, please don't send me off on XML Serialization, I want binary for a reason. :)

In the following code (and I don't even know if its correct ... it does compile), I'm trying to serialize and write a list of my class to a file and then read it back

I'm understanding everything until we get to the reading part ... every fricking example on the internet writes just one record and reads it back.

Down at line 35 ... I'm not sure how write the loop to tell if I've reached the end of my file or if I even need to be concerned with it because serialization does the entire file ... but if it does the entire file, then supplying just record isn't going to cut it.

public void WriteRecordsToFile()
            //Create the file name ...
            string fn = Properties.Settings.Default.ExecutionPath + "IIVRecords.DAT";

            Stream stream = File.Open(fn, FileMode.Create);
            //Make the formatter ...
            BinaryFormatter bformatter = new BinaryFormatter();

            if (reclist.Count > 0)
                for (int x = 0; x < reclist.Count; x++)
                    record = reclist[x];
                    bformatter.Serialize(stream, record);

        public void ReadRecordsFromFile()
            record = null;

            //create the filename path
            string fn = Properties.Settings.Default.ExecutionPath + "IIVRecords.DAT";

            //Open the file written above and read values from it.
            stream = File.Open(fn, FileMode.Open);
            bformatter = new BinaryFormatter();

            record = (RecordClass)bformatter.Deserialize(stream);

Any help, improvements, comments are appreciated.

6 Years
Discussion Span
Last Post by nick.crane

On deserialize (assuming no errors occur) each record must be read in turn.
The stream pointer should be pointing to the start of the next record after reading the first.
Just add each record to your list in turn and read the next.

I would recommend that you first serialize a record count.
Then you know how many records are in the list when you deserialize (don't forget to read the count first).
Or loop until end of file stream.

Alternatively, just serialize the whole array (or list) in one step and deserialize that.

Votes + Comments
both good points..if i'm using a list i would serialize the whole thing
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.