Reputation: 1216
I have 2 programs that use serialization, in 2 different projects. Program 1 serializes and deserializes an array of a class called Quiz.Both project have the the Quiz Class. Program 2 only deserializes what Program 1 serialized:
private void loadSerialize(object sender, EventArgs e)
{
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new System.IO.FileStream("DataFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
Quiz[] obj = (Quiz[]) formatter.Deserialize(stream);
for(int i = 0; i< obj.Length; i++)
{
quizes.Add(obj[i]);
}
stream.Close();
}
private void saveSerialize(object sender, FormClosedEventArgs e) {
Quiz[] obj = quizes.ToArray();
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("DataFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
both programs have the "loadSerialize" function while only Program1 has the "saveSerialize" function. I`m getting a serializationException when I try to deserialize the file in Program2. Saying that(message erro was in portuguese so I translated it to english): Couldnt find the assembly 'infoAplicadaEnsino, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. How can I deserialize in Program2?
Upvotes: 2
Views: 838
Reputation: 112259
You probably have 2 copies of the Quiz
class in the two solutions (or projects). Instead, create a third solution (or project) with a class library project. Class library projects create DLLs instead of EXEs. Move all the things used in common in your 2 solutions (or projects) to this third one and then reference this third project in the existing ones. So you will have only one Quiz
class (and also only one loadSerialize
method).
This will not only make your serialization/deserialization work, but will make it easier to keep the things consistent (only one version of Quiz
to maintain).
Upvotes: 3
Reputation: 91
Same class members, name and namespace is not enough for deserialization to work, the assembly must also match, this is how BinaryFormatter
is designed. You can fix this by extracting Quiz
class to a separate class library project and reference the new project by both program projects.
Upvotes: 5