日期:2010-07-30 浏览次数:20485 次
配置类或数据类都需要可序列化。通常,序列化有三种方式,序列化和反序列化的过程可以做成一个静态类,如下:
Public Class SerializeHelperClass SerializeHelper
Private Sub New()Sub New()
End Sub
Private Shared Function GetXML()Function GetXML(ByVal obj As Object) As String
Dim mSerializer As New System.Xml.Serialization.XmlSerializer(obj.GetType)
Dim mStringWriter As New System.IO.StringWriter
mSerializer.Serialize(mStringWriter, obj)
Return mStringWriter.ToString
End Function
Private Shared Function GetObj()Function GetObj(ByVal objtype As Type, ByVal xml As String) As Object
Dim mSerializer As New System.Xml.Serialization.XmlSerializer(objtype)
Dim mStringReader As New System.IO.StringReader(xml)
Return mSerializer.Deserialize(mStringReader)
End Function
Private Shared Sub SaveXmlFile()Sub SaveXmlFile(ByVal filename As String, ByVal obj As Object)
Dim XmlWriter As New System.IO.StreamWriter(filename, False)
XmlWriter.Write(GetXML(obj))
XmlWriter.Close()
End Sub
Private Shared Function LoadXmlFile()Function LoadXmlFile(ByVal filename As String, ByVal objtype As Type) As Object
Dim XmlReader As New System.IO.StreamReader(filename, System.Text.Encoding.Default)
Dim mObj As Object
mObj = GetObj(objtype, XmlReader.ReadToEnd)
XmlReader.Close()
Return mObj
End Function
Private Shared Sub SaveSerializerFile()Sub SaveSerializerFile(ByVal filename As String, ByVal formatter As System.Runtime.Serialization.IFormatter, ByVal obj As Object)
Dim mFileStream As System.IO.Stream = System.IO.File.Open(filename, System.IO.FileMode.Create)
formatter.Serialize(mFileStream, obj)
mFileStream.Close()
End Sub
Private Shared Function LoadDeSerializeFile()Function LoadDeSerializeFile(ByVal FileName As String, ByVal formatter As System.Runtime.Serialization.IFormatter) As Object
Dim mFileStream As System.IO.Stream = System.IO.File.Open(FileName, System.IO.FileMode.Open)
Dim mObj As Object
mObj = formatter.Deserialize(mFileStream)
mFileStream.Close()
Return mObj
End Function
Public Shared Function Clone()Function Clone(ByVal obj As Object) As Object
Dim mFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
Dim mMemoryStream As New System.IO.MemoryStream
mFormatter.Serialize(mMemoryStream, obj)
mMemoryStream.Position = 0
Return mFormatter.Deserialize(mMemoryStream)
End Funct