I am trying to learn how to do binary serialziation.
This exception gets thrown every time I try to deserialize an object I previously serialized:
Binary stream '161' does not contain a valid BinaryHeader. Possible causes are invalid
stream or object version change between serialization and deserialization.
This is the header of my class:
[Serializable]
public ref class Servis{
String ^_nazivServisa;
DateTime ^_datumOsnivanjaServisa;
double _popustZaStalneKlijente;
[NonSerialized] List<Izvjestaj ^> ^_izvjestaji;
[NonSerialized] List<StalniKlijent ^> ^_stalniKlijenti;
[NonSerialized] List<Vozilo ^> ^_poznataVozila;
this is GetObjectData method, set as public inside the same class:
virtual void GetObjectData(SerializationInfo^ info, StreamingContext context){
info->AddValue("Naziv servisa", _nazivServisa);
info->AddValue("Datum osnivanja servisa", _datumOsnivanjaServisa->ToString());
info->AddValue("Popust za stalne klijente", _popustZaStalneKlijente);
}
this is the constructor used for deserialization:
protected:
Servis(SerializationInfo ^info, StreamingContext context){
_nazivServisa = info->GetString("Naziv servisa");
_datumOsnivanjaServisa = Convert::ToDateTime(info->GetString("Popust za stalne klijente"));
_popustZaStalneKlijente = info->GetDouble("Popust za stalne klijente");
_izvjestaji=gcnew List<Izvjestaj ^>;
_stalniKlijenti = gcnew List<StalniKlijent ^>;
_poznataVozila = gcnew List<Vozilo ^>;
}
And this is the block of code in which I try to open a file and deserialize it; if the file doesn't exist a new dialog is shown to input some data, and then the file is serialized
BinaryFormatter ^b = gcnew BinaryFormatter;
try{
FileStream ^fs = gcnew FileStream("..\\Datoteke\\Servis.dat", FileMode::Open);
_servis = dynamic_cast<Servis ^>(b->Deserialize(fs));
fs->Close();
}
catch(FileNotFoundException ^exc){
KreirajServis();
try{
FileStream ^fs = gcnew FileStream("..\\Datoteke\\Servis.dat", FileMode::Create);
b->Serialize(fs, _servis);
fs->Close();
}
}
}
private: void KreirajServis(){
PrvoPokretanje ^p = gcnew PrvoPokretanje();
p->ShowDialog();
_servis=p->dajServis();
}
Now, the exception message says that the possible causes are invalid stream or object version change between serialization and deserialization. Since I haven't touched my class between serialization and deserialization, I'm guessing the problem is with the stream, it being invalit (or is it something else!?).
Could someone, please, point me in the right direction, it would be much appreciated. :)