0

I have an enum type in my first assembly, like below:

public enum MyEnum
{
   ONE,
   TWO,
   THREE
}

Since I wanted to extend my application I have decided to move that to a different assembly (dll) and link it to my first assembly.

When I do that I get a weird result, when I desterilize classes that were serialized when the enum was in the first assembly, they all return first enum member by default.

Is there a solution on how to fix that? I even tried to parse it like:

(MyEnum)Enum.Parse(typeof(MyEnum), serializer.MyEnumType.ToString());

It has no effect.

PS. I use a binary serializer and the enum is in the same namespace and still have the same name.

[Serializable]
    public class testClass
    {
        public MyEnum En { set; get; }
    }

    public class test
    {
        void Serialize(string file)
        {
            testClass ser = new testClass();
            IFormatter formatter = new BinaryFormatter();
            System.IO.FileStream stream = new FileStream(file, FileMode.Create, System.IO.FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, ser);
            stream.Close();
        }
        void DeSerialize(string file)
        {
            IFormatter formatter = new BinaryFormatter();
            testClass ser = new testClass();
            System.IO.FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None);
            ser = (testClass)formatter.Deserialize(stream);
            stream.Close();
        }
    }
xmojmr
  • 8,073
  • 5
  • 31
  • 54
Glen
  • 89
  • 6
  • Possible duplicate: http://stackoverflow.com/questions/12737602/cant-deserialize-with-binaryformatter-after-changing-namespace-of-class – David Tansey Mar 19 '15 at 02:40
  • Also see: http://stackoverflow.com/questions/25701481/is-it-possible-to-recover-an-object-serialized-via-binaryformatter-after-chang – David Tansey Mar 19 '15 at 02:41
  • Problem is, namespace is the same and so is the class and enum name. – Glen Mar 19 '15 at 02:51
  • @Glen if you look close at one of those posts you'll see that the remedy code also changes the _assembly name_ of the object to be deserialized. I think this is the 'thing' that applies in your case. – David Tansey Mar 19 '15 at 03:42
  • 1
    @Glen -- look at the answer which indicates 'you forgot to change the assembly name'. – David Tansey Mar 19 '15 at 03:44

1 Answers1

2

BinaryFormatter takes into consideration various information about the assembly itself in the serialization process, not just the type's namespace and such. Your problem is occurring because you moved the type to a new assembly so the "serialized" representation is no longer correct.

See this question for an answer to work around this.

Community
  • 1
  • 1
9ee1
  • 1,078
  • 1
  • 10
  • 25