2

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?

2 Answers 2

5

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.

2
  • 1
    Indeed. There is also lazy option - just add the first exe as reference to the second project. Nov 15, 2015 at 20:49
  • Now I`m getting the erro that I cant acess the file because its being used by another process when I try to serialize the object. Edit: NVM, solved when deleted the previous serialized file. Nov 15, 2015 at 20:56
3

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.