Feedback

C# - Zum De/Serialisieren von Objekten

Veröffentlicht von am 2/24/2006
(1 Bewertungen)
Zum De/Serialisieren von Objekten
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Vertexwahn
{
    public class Serializer
    {
        public static byte[] SerializeIt(object obj)
        {
            try
            {
                MemoryStream bout = new MemoryStream();
                BinaryWriter objOut = new BinaryWriter(bout);
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objOut.BaseStream, obj);
                objOut.Close();
                return bout.ToArray();
            }
            catch (IOException e)
            {
                throw new ApplicationException("Serialization failed: " + e.Message);
            }
        }

        public static object DeserializeIt(byte[] data)
        {
            if (data == null)
                return null;
            try
            {
                MemoryStream bin = new MemoryStream(data);
                BinaryFormatter formatter = new BinaryFormatter();
                object obj = formatter.Deserialize(bin);
                bin.Close();
                return obj;
            }
            catch (IOException e)
            {
                throw new ApplicationException("Deserialization failed: " +
                                               e.Message);
            }
            catch (Exception e)
            {
                throw new ApplicationException("Class not found: " + e.Message);
            }
        }
    }
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!