C# – End of stream encountered before parsing was completed

c

I'm trying to read multiple objects from a file with this code:

List<Alarm> list = new List<Alarm>();
BinaryFormatter serializer = new BinaryFormatter();

using (FileStream stream = File.OpenRead("//my File here"))
{
    while (stream.Position < stream.Length)
    {
        list.Add((Alarm)serializer.Deserialize(stream));
    }
}

However, everytime I try to run this code, I get an error like "End of Stream encountered before parsing was completed". Note that there is a thread existing already which suggests setting the streams position to 0 after each iteration, but that won't work for me obviously, or I would land in an infinite loop.

What am I doing wrong here? The code itself works if I leave out the while loop, but obviously in a file with multiple objects I don't just want to get a single one out of my file, but rather all of them.

Any advice?

Edit: On demand:

Serialization.

//Fetches Data from my GUI, creates a valid Alarm object
Alarm alarm = new Alarm(this.noticeBox.Text, date.Year, date.Month, date.Day, (int)this.hourPicker.Value, (int)this.minutePicker.Value);

var serializer = new BinaryFormatter();

using (FileStream stream = "//file"))
{
        serializer.Serialize(stream, alarm);
}

Best Answer

If what you have serialized is the List of Alarms (and not a series of individual Alarms), which is more than probable, then you only have to deserialize that:

using (FileStream stream = File.OpenRead("//my File here"))
{
   list = (List<Alarm>)serializer.Deserialize(stream));
}

Otherwise, if you have serialized standalone Alarm objects, your code should work (each of them would be an object graph by itself, which seems not to be the case)

Edit: everything in what you posted seems to be fine. I've added a fiddle here ( https://dotnetfiddle.net/bGWOOO ) which demonstrate how the method you are using works (I used a MemoryStream instead of a FileStream for obvious reasons, but it should not matter). So there's something else wrong: either the stream is not being correctly written to disk, or not being correctly read, but it's not about the code you posted, definitely.

Update

Just for further reference as to why this answer was chosen (as the real answer was in the comments/chat):

In the serializer, you are creating the file everytime and replacing the contents (not shown in the question, but guessed out in the comments), so the answer was correctly appending to the file, something like this:

using (FileStream stream = new FileStream("** path to file here**", FileMode.Append,  FileAccess.Write, FileShare.Write))
{
  // write the serialized data to the stream
}
Related Topic