每天为梦想努力一点点

【Demo Code】Serialize and Deserialize in .NET

上一篇 / 下一篇  2006-04-28 15:37:20 / 天气: 晴朗 / 心情: 高兴 / 个人分类:.NET 编程

It may very useful to serialize the object to byte and save it disk in some condition, so here is some demo code.

 
Serialize the exception to byte use the binary formatter:

    Private Shared Function SerializeTheException(ByVal ex As Exception) As Byte()
        Dim returnArray() As Byte
        Dim ms As New System.IO.MemoryStream
        Dim b As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        b.Serialize(ms, ex)
        ms.Seek(0, 0)
        returnArray = ms.ToArray
        Return returnArray
    End Function

 

    Private Shared Function DeSerializeTheException(ByVal exMeta As Byte()) As Exception
        Dim b As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Return CType(b.Deserialize(New IO.MemoryStream(exMeta)), Exception)
    End Function

 
Serialize the exception to byte use the xml formatter:

    Public Shared Function SerializeTheObject(ByVal value As Object) As Byte()
        Dim serializer As System.Xml.Serialization.XmlSerializer
        Dim types(0) As Type
        types(0) = value.GetType()

        'Serialize
        serializer = System.Xml.Serialization.XmlSerializer.FromTypes(types)(0)
        Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream
        serializer.Serialize(stream, value)

        ' Return
        Return stream.ToArray()
    End Function

 

    Public Shared Function DeserializeTheObject(ByVal bytes As Byte(), ByVal returnType As System.Type) As Object
        Dim serializer As System.Xml.Serialization.XmlSerializer
        Dim types(0) As Type
        types(0) = returnType

        ' Deserialize
        serializer = System.Xml.Serialization.XmlSerializer.FromTypes(types)(0)
        Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(bytes, False)

        ' Return
        Return serializer.Deserialize(stream)

    End Function


TAG: 电脑网络 序列化 编程相关

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

数据统计

  • 访问量: 33842
  • 日志数: 82
  • 图片数: 5
  • 文件数: 7
  • 书签数: 14
  • 建立时间: 2006-04-18
  • 更新时间: 2007-03-30

RSS订阅

Open Toolbar