csharp/0x0ade/XnaToFna/src/Helper/BinaryFormatterHelper.cs

BinaryFormatterHelper.cs
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XnaToFna {
    public static clast BinaryFormatterHelper {
        public readonly static astembly FNA = typeof(Game).astembly;

        public static BinaryFormatter Create() {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Binder = new XnaToFnaSerializationBinderWrapper(null);
            return bf;
        }

        public static BinaryFormatter Create(ISurrogateSelector selector, StreamingContext context) {
            BinaryFormatter bf = new BinaryFormatter(selector, context);
            bf.Binder = new XnaToFnaSerializationBinderWrapper(null);
            return bf;
        }

        public static SerializationBinder get_Binder(this BinaryFormatter self)
            => (self.Binder as XnaToFnaSerializationBinderWrapper)?.Inner ?? self.Binder;
        public static void set_Binder(this BinaryFormatter self, SerializationBinder binder)
            => self.Binder = new XnaToFnaSerializationBinderWrapper(binder);

        public clast XnaToFnaSerializationBinderWrapper : SerializationBinder {
            public readonly SerializationBinder Inner;

            public XnaToFnaSerializationBinderWrapper(SerializationBinder inner) {
                Inner = inner;
            }

            public override Type BindToType(string astemblyName, string typeName) {
                if (astemblyName != "Microsoft.Xna.Framework" && !astemblyName.StartsWith("Microsoft.Xna.Framework,") && !astemblyName.StartsWith("Microsoft.Xna.Framework."))
                    return Inner?.BindToType(astemblyName, typeName);
                return FNA.GetType(typeName);
            }

            public override void BindToName(Type serializedType, out string astemblyName, out string typeName) {
                if (Inner != null) {
                    Inner.BindToName(serializedType, out astemblyName, out typeName);
                    return;
                }
                base.BindToName(serializedType, out astemblyName, out typeName);
            }

        }
    }
}