每天为梦想努力一点点
【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:
电脑网络
序列化
编程相关