BinaryFormatter - 是否可以在没有程序集的情况下反序列化已知类?

2023-12-24

我目前正在尝试与一个程序进行互操作,该程序在首先使用 C# 的 BinaryFormatter 格式化数据后通过网络发送数据。这是一个愚蠢的想法,我讨厌它,但我必须与它进行互操作。

我知道该类型是什么样子,我知道它的确切布局。但由于各种原因,我无法在程序中添加对该特定程序集的引用。

考虑到 BinaryFormatter 与特定类型/版本的紧密耦合,尽管知道数据结构,但我似乎找不到办法让它反序列化。

我目前正在考虑创建一个具有所有正确属性的假程序集并尝试将其链接到(看起来真的很混乱),或者手动尝试通过二进制流并提取我正在寻找的值(我正在查看 MS 的相关文档,布局一目了然)。

还有其他伟大的想法,或者过去有人在这方面取得过成功吗?似乎我知道我需要的所有信息,而 BinaryFormatter 对此却非常脆弱。

edit:

要回答下面的问题(顺便说一句,这是一个很好的观点),有几个原因。

  1. 项目清洁度。将 5MB 的引用添加到一个功能外部的 .exe 有点不对劲。

  2. 我正在交互操作的设备有部署在世界各地的各种版本。我关心的项目的内部数据结构在所有项目中都是相同的,但程序集的版本不同,导致 BinaryFormatter 损坏。我可以将二进制流转换为字符串,搜索版本号,然后加载正确的版本,但现在我有十几个 .exe 等待我加载正确的版本。那么这个方案就不是非常面向未来的(好吧,整个方案并不是真正面向未来的,但我至少想抽象出 BinaryFormatter 的一些脆弱性以使我的工作更容易)。仅仅写这个回复就让我考虑使用 emmit 或类似的方法来动态创建自定义程序集......但是,伙计,必须有一种更简单的方法,对吗?我实际上是在中等大小的数据结构中寻找几个布尔值。

  3. 对象的变量通过 get/set 属性公开,这些属性具有一些逻辑,并尝试进行函数调用并更新我这边可能不存在的其他对象(又名, get 获取我需要的值,但也会触发通知会影响链接的依赖项,我的应用程序中可能会出现异常。谈论代码气味!)。它变成了一个依赖/实现的兔子洞。

edit2:制造商正在与我合作,使他们的系统变得更好,但是当我们宣传“与 X 兼容”时,我们希望它只与 X 兼容,而不需要特定版本。特别是对于我们的一些严格版本控制的客户系统,仅仅更新有问题的应用程序就成为一项重大工作。


正如您在对问题的评论中推测的那样 SerializationSurrogate 和 SerializationBinder 可以帮助您实现这一目标。鉴于您只对几个属性感兴趣,您可以反序列化为代理类,通过枚举传递给 SerializationSurrogate 的 SerializationInfo 来填充该代理类。不幸的是,它只能让你到达那里的一部分。

问题是访问属性不会触发序列化对象中的任何副作用,因为您只是使用 SerializationSurrogate 访问数据 - 没有任何二进制代码被执行。下面的快速和肮脏的测试代码说明了这个问题:

namespace BinaryProxy
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;

    [Serializable]
    class TestClass
    {


        public bool mvalue;

        public TestClass(bool value)
        {
            BoolValue = value;
        }

        public bool BoolValue
        {
            get
            {
                // won't happen
                SideEffect = DateTime.Now.ToString();
                return mvalue;
            }

            set
            {
                mvalue = value;
            }
        }

        public string SideEffect { get; set; }

    }

    class ProxyTestClass
    {
        private Dictionary<string, object> data = new Dictionary<string, object>();

        public Object GetData(string name)
        {
            if(data.ContainsKey(name))
            {
                return data[name];
            }
            return null;
        }
        public void SetData(string name, object value)
        {
            data[name] = value;
        }

        public IEnumerable<KeyValuePair<string, object>> Dump()
        {
            return data;
        }
    }

    class SurrogateTestClassConstructor : ISerializationSurrogate
    {
        private ProxyTestClass mProxy;
        /// <summary>
        /// Populates the provided <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the object.
        /// </summary>
        /// <param name="obj">The object to serialize. </param>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data. </param>
        /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization. </param>
        /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception>
        public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Populates the object using the information in the <see cref="T:System.Runtime.Serialization.SerializationInfo"/>.
        /// </summary>
        /// <returns>
        /// The populated deserialized object.
        /// </returns>
        /// <param name="obj">The object to populate. </param>
        /// <param name="info">The information to populate the object. </param>
        /// <param name="context">The source from which the object is deserialized. </param>
        /// <param name="selector">The surrogate selector where the search for a compatible surrogate begins. </param>
        /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception>
        public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        {
            if (mProxy == null) mProxy = new ProxyTestClass();
            var en = info.GetEnumerator();
            while (en.MoveNext())
            {
                mProxy.SetData(en.Current.Name, en.Current.Value);


            }
            return mProxy;

        }



    }

    sealed class DeserializeBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {


            return typeof(ProxyTestClass);
        }
    }

    static class Program
    {

        static void Main()
        {
            var tc = new TestClass(true);
            byte[] serialized;
            using (var fs = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(fs, tc);
                serialized = fs.ToArray();

                var surrSel = new SurrogateSelector();
                surrSel.AddSurrogate(typeof(ProxyTestClass),
                    new StreamingContext(StreamingContextStates.All), new SurrogateTestClassConstructor());

                using (var fs2 = new MemoryStream(serialized))
                {
                    var formatter2 = new BinaryFormatter();
                    formatter2.Binder = new DeserializeBinder();
                    formatter2.SurrogateSelector = surrSel;
                    var deser = formatter2.Deserialize(fs2) as ProxyTestClass;
                    foreach (var c in deser.Dump())
                    {
                        Console.WriteLine("{0} = {1}", c.Key, c.Value);
                    }
                }

            }

        }
    }
}

在上面的例子中,TestClass' SideEffect支持字段将保持为空。

如果您不需要副作用而只想访问某些字段的值,那么该方法在某种程度上是可行的。否则,除了遵循 Jon Skeet 的建议之外,我想不出任何其他可行的解决方案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

BinaryFormatter - 是否可以在没有程序集的情况下反序列化已知类? 的相关文章

随机推荐