Hi @Deepak Rane (drane) , Welcome to Microsoft Q&A,
In C#, DataContractSerializer and BinaryFormatter work differently. BinaryFormatter uses SerializationBinder for type binding, while DataContractSerializer does not support similar binding. Instead, DataContractSerializer uses data contracts ([DataContract] and [DataMember]) for serialization and deserialization, and requires type matching.
You can achieve similar functionality by solving the type binding problem in a custom way.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
[DataContract]
public class Class2
{
[DataMember]
public string Property { get; set; }
}
public class CustomResolver
{
public Type ResolveType(string typeName)
{
if (typeName == "OldNamespace.Class2")
{
return typeof(Class2);
}
throw new InvalidOperationException($"Unknown type: {typeName}");
}
}
public class Program
{
public static void Main()
{
var resolver = new CustomResolver();
var typeName = "OldNamespace.Class2";
var resolvedType = resolver.ResolveType(typeName);
var serializer = new DataContractSerializer(resolvedType);
using (var stream = new FileStream("data.xml", FileMode.Open))
{
var result = serializer.ReadObject(stream);
var dc = result as Class2;
Console.WriteLine(dc?.Property);
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.