1

Having this class:

namespace CoolNamespace
{
    [Serializable]
    public class MyClass
    {
        public string Data { get; set; }
        public int Age { get; set; }
    }
}

In the class Program.cs from a console application, I am serializing it.

namespace TestSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass c = new MyClass();
            c.Data = "test";
            c.Age = 6;

            byte[] s = Serialize(c);
            File.WriteAllBytes(@"C:\Temp\test.txt", s);
        }

        public static byte[] Serialize(object data)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            using (MemoryStream memoryStream = new MemoryStream())
            {
                new BinaryFormatter().Serialize((Stream)memoryStream, data);
                memoryStream.Seek(0L, SeekOrigin.Begin);
                return memoryStream.GetBuffer();
            }
        }
    }
}

But I don't understand wht in the serialized class I am seeing the namespace of the class Program.cs? here is the serialized class:

ÿÿÿÿ HTestSerialization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null CoolNamespace.MyClass
k__BackingFieldk__BackingField test

So if I want to deserialize it in another namespace, it would fail with th error:

System.Runtime.Serialization.SerializationException: Unable to find assembly 'TestSerialization, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

So how can I avoid this issue?

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • [Examples](https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file) – dr.null Aug 23 '21 at 17:27
  • @dr.null the serialization is already in place and it cannot be changed. – Buda Gavril Aug 23 '21 at 20:11
  • @BudaGavril, In this case, you are going to have to make a custom deserializer that ignore assembly/namespace informations. – vernou Aug 24 '21 at 07:21
  • Maybe [KGySoft.CoreLibraries](https://github.com/koszeggy/KGySoft.CoreLibraries#serialization) can do that... or a good start. – vernou Aug 24 '21 at 07:21
  • You could implement a [SerializationBinder](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.serializationbinder?view=net-5.0). – Steeeve Aug 24 '21 at 17:01

0 Answers0