C#オブジェクトをbyte[],byte[]に変換してオブジェクトを復元

3190 ワード

        /// <summary> 

        ///  object , byte[]         

        /// </summary> 

        /// <param name="obj"> </param>         

        /// <returns></returns> 

        public static byte[] ObjectToBytes(object obj)

        {

            using (MemoryStream ms = new MemoryStream())

            {

                IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer();

            }

        }



        /// <summary> 

        ///  byte[]          

        /// </summary>

        /// <param name="Bytes"></param>         

        /// <returns></returns> 

        public static object BytesToObject(byte[] Bytes)

        {

            using (MemoryStream ms = new MemoryStream(Bytes))

            {

                IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms);

            }

        }