How to deserialize byte[] into generic object to be cast at method call

20,023

The type you want to deserialize must be known at compile time.. So your method can be like:

private T Deserialize<T>(byte[] param)
{
    using (MemoryStream ms = new MemoryStream(param))
    {
        IFormatter br = new BinaryFormatter();
        return (T)br.Deserialize(ms);
    }
}

Now you can use it like

var myclass = Deserialize<MyClass>(buf);
Share:
20,023
cSkillzMartin
Author by

cSkillzMartin

Microsoft .NET technologies (C#, MVC), MS-SQL, and complementary products like Azure Cloud, WCF, Web API, VB.NET, WebForms, IIS, SQL Server, bootstrap, jQuery, HTML, XML and .NET Core are at the heart of my expertise. I also use and am familiar with web and mobile technologies implemented on Linux and Mobile platforms but not limited to. My primary development duties include application design and architecture, cloud migration, legacy updates, application maintenance, as well as supporting enterprise systems of various technology stacks. In addition to my practical working expertise, I regularly undergo professional and personal training to not only grow my skills becoming a more advanced technical resource, but maintain peripheral skills and keep current skills up to date. Personal projects include building native mobile applications, containerized (Docker) application development, machine learning with TensorFlow, Drupal modules, cryptography, authentication and authorization implementation, proxied communication, as well as research on algorithm design. A field I am particularly interested in is image recognition. My professional experience is backed by academic training in object oriented analysis and design, relational database design, leadership, quantitative analysis, and project management. All of which has given me the ability to quickly learn new coding languages, system architectures, organizational cultures, design patterns, deployment paths, and most importantly how to solve problems through analysis and critical thinking. I am a candidate who does not require motivation and am an employee who does good work because I am engaged with what I do. My goal is to live the life of the master, to continually improve my knowledge, skills and quality of execution, to never think I have achieved mastery but know that I have journeyed far beyond my starting point.

Updated on August 24, 2022

Comments

  • cSkillzMartin
    cSkillzMartin almost 2 years

    I am working on an object encryption class. I have everything worked out but I want to be able to encrypt/decrypt any object type with one deserialize method. As of now the only thing holding me up is the deserialize method. I have the function returning type(object) in the hopes of returning a weak typed object. It works as long as I cast the type during the return value assignment, but If I deserialize into type 'object' the result is byte[].

    This means that I have to write a deserialize method for every object(T) i want to operate on. What I want to do is pass Type(T) as a parameter to the deserialize method so I can deserialize into object(T), then return the typed object.

    The problem is that using a typed parameter is apparently not allowed.
    If I do obj = (type.GetType())br.Deserialize(ms); I get ; expected between '(object(T)) and br.'.

    If I do obj = (br.Deserialize(ms) as type); I get The type of namespace "type" could not be found. (are you missing a using directive or an assembly reference?)

    or I get a symbol can not be resolved error. Any help is appreciated. Full code is below.

            private byte[] serialize(object param)
        {
            byte[] encMsg = null;
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter br = new BinaryFormatter();
                br.Serialize(ms, param);
                encMsg = ms.ToArray();
            }
    
            return encMsg;
        }
    
        private object deserialize(byte[] param)
        {
            object obj = null;
            using (MemoryStream ms = new MemoryStream(param))
            {
                IFormatter br = new BinaryFormatter();
                obj = (br.Deserialize(ms) as myObject);
            }
    
            return obj;
        }
    
        private byte[] encrypt(byte[] param)
        {
            byte[] encMsg = null;
            using (Aes myAes = Aes.Create())
            {
                myAes.Padding = PaddingMode.ANSIX923;
                ICryptoTransform autoBot = myAes.CreateEncryptor(myAes.Key, myAes.IV);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, autoBot, CryptoStreamMode.Write))
                    {
                        cs.Write(param, 0, (int)param.Length);
                    }
                    encMsg = ms.ToArray();
                }
            }
            return encMsg;
        }
    
        private byte[] decrypt(byte[] key, byte[] iv, byte[] param)
        {
            byte[] dcparam = null;
            using (Aes myAes = Aes.Create())
            {
                myAes.Padding = PaddingMode.ANSIX923;
                ICryptoTransform autoBot = myAes.CreateDecryptor(key, iv);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, autoBot, CryptoStreamMode.Write))
                    {
                        cs.Write(param, 0, (int)param.Length);
                    }
                    dcparam = ms.ToArray();
                }
            }
            return dcparam;
        }
    
  • JamieSee
    JamieSee over 8 years
    You're missing the <T> from the method signature.
  • nuiun
    nuiun over 8 years
    @JamieSee technically it's not required on the method if your class already has the type parameter - in fact it will generate a compiler warning. But OP did say he wanted it on the method :)
  • cSkillzMartin
    cSkillzMartin over 8 years
    My notifications are going to spam. That worked like a charm. Thank you!
  • JPocoata
    JPocoata almost 3 years
    In .NET 5, the method new BinaryFormatter().Deserialize(ms) is deprecated because is unsecure docs.microsoft.com/en-us/dotnet/standard/serialization/…