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);
                }
            }
            stream.Close();
        }


        public void ReadRecordsFromFile()
        {
            record = null;
            reclist.Clear();

            //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);
            stream.Close();
        }

Any help, improvements, comments are appreciated.

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.

commented: both good points..if i'm using a list i would serialize the whole thing +2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.