Have a Snippet?

Keep, track and share your code snippets with your friends



C#: Serialize Helper Share on Vkontakte

Misc helper methods for deserializing and serializing objects.

 public static class SerializeHelpers
    {
        ///  
        /// Takes an array of bytes and attempts to deserialize it into an object. 
        ///  
        ///  
        ///  
        public static T DeserializeFromByteArray(byte[] source) where T : class
        {
            return DeserializeFromByteArray(source, s => { }, r => { });
        }

        ///  
        /// Takes an array of bytes and attempts to deserialize it into an object. 
        ///  
        ///  
        /// 
        /// 
        ///  
        public static T DeserializeFromByteArray(byte[] source, Action deserializingAction, Action deserializedAction) where T : class
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (source.Length <= 0)
                throw new ArgumentException("Can not deserialize from an empty byte array!", "source");
            if (deserializingAction == null)
                throw new ArgumentNullException("deserializingAction");
            if (deserializedAction == null)
                throw new ArgumentNullException("deserializedAction");

            deserializingAction(source);

            var ms = new MemoryStream();
            ms.Write(source, 0, source.Length);
            ms.Seek(0, SeekOrigin.Begin);
            var b = new BinaryFormatter();
            var result = (T)b.Deserialize(ms);

            deserializedAction(result);

            return result;
        }

        ///  
        /// Takes any object and attempts to serialize it into an array of bytes. 
        ///  
        ///  
        ///  
        ///  
        public static byte[] SerializeToByteArray(T source) where T : class
        {
            return SerializeToByteArray(source, s => { }, r => { });
        }

        ///  
        /// Takes any object and attempts to serialize it into an array of bytes. 
        ///  
        ///  
        /// 
        /// 
        ///  
        ///  
        public static byte[] SerializeToByteArray(T source, Action serializingAction, Action serializedAction) where T : class
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (serializingAction == null)
                throw new ArgumentNullException("serializingAction");
            if (serializedAction == null)
                throw new ArgumentNullException("serializedAction");

            serializingAction(source);

            var b = new BinaryFormatter();
            var ms = new MemoryStream();
            b.Serialize(ms, source);
            ms.Seek(0, SeekOrigin.Begin);
            var result = ms.ToArray();

            serializedAction(result);

            return result;
        }

        ///  
        /// Takes any object and attempts to serialize it into a string. 
        ///  
        ///  
        ///  
        ///  
        public static string SerializeToString(T source) where T : class
        {
            return SerializeToString(source, s => { }, r => { });
        }

        ///  
        /// Takes any object and attempts to serialize it into a string. 
        ///  
        ///  
        /// 
        /// 
        ///  
        ///  
        public static string SerializeToString(T source, Action serializingAction, Action serializedAction) where T : class
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (serializingAction == null)
                throw new ArgumentNullException("serializingAction");
            if (serializedAction == null)
                throw new ArgumentNullException("serializedAction");

            serializingAction(source);

            string serialString = null;
            using (var ms1 = new System.IO.MemoryStream())
            {
                var b = new BinaryFormatter();
                b.Serialize(ms1, source);
                var arrayByte = ms1.ToArray();
                serialString = Convert.ToBase64String(arrayByte);
            }

            serializedAction(serialString);

            return serialString;
        }

        ///  
        /// Takes a string and attempts to deserialize it into an object. 
        ///  
        ///  
        ///  
        public static T DeserializeFromString(string source) where T : class
        {
            return DeserializeFromString(source, s => { }, r => { });
        }

        ///  
        /// Takes a string and attempts to deserialize it into an object. 
        ///  
        ///  
        /// 
        /// 
        ///  
        public static T DeserializeFromString(string source, Action deserializingAction, Action deserializedAction) where T : class
        {
            if (string.IsNullOrEmpty(source))
                throw new ArgumentNullException("source");
            if (source.Length <= 0)
                throw new ArgumentException("Can not deserialize from an empty byte array!", "source");
            if (deserializingAction == null)
                throw new ArgumentNullException("deserializingAction");
            if (deserializedAction == null)
                throw new ArgumentNullException("deserializedAction");

            deserializingAction(source);

            T deserializedObject = null;
            var arrayByte = Convert.FromBase64String(source);
            using (var ms1 = new MemoryStream(arrayByte))
            {
                var b = new BinaryFormatter();
                deserializedObject = (T)b.Deserialize(ms1);
            }

            deserializedAction(deserializedObject);

            return deserializedObject;
        }

        public static string SerializeToXml(object source)
        {
            return SerializeToXml(false);
        }

        public static string SerializeToXml(object source, bool omitXmlDeclaration)
        {
            var xmlString = new StringBuilder();
            var xmlSettings = new XmlWriterSettings
                                  {
                                      Encoding = new UTF8Encoding(),
                                      OmitXmlDeclaration = omitXmlDeclaration
                                  };
            var xmlWriter = XmlWriter.Create(xmlString, xmlSettings);
            var serializer = new XmlSerializer(source.GetType());

            if (xmlWriter != null)
            {
                serializer.Serialize(xmlWriter, source);
                xmlWriter.Close();                
            }

            return xmlString.ToString();
        }

        public static T DeserializeFromXml(string source) where T : class
        {
            var serializer = new XmlSerializer(typeof(T));
            var reader = new StringReader(source);
            T result = (T) serializer.Deserialize(reader);
            reader.Dispose();
            return result;
        }
    }


Tag: C#, Serialization, extensions

0 Comments