PDA

Click to See Complete Forum and Search --> : Saving Question...


Hinder
Jan 11th, 2003, 11:17 PM
Is there a way to save a complete class to a binary file without having to save each element in the class? Kinda like in VB6, I could place everything in a TYPE and just save the whole TYPE in one big binary chunk.. Is there anything simular to this method of saving data in vb.net?

Edneeis
Jan 12th, 2003, 12:42 AM
You can serialize an object to disk or memory as long as it has the Serializable attribute. I'll post an example in a sec. You can also serialize things to xml if you want.

Edneeis
Jan 12th, 2003, 01:03 AM
'the example class
'make sure the class has the serializable attribute
<Serializable()> _
Public Class Tester
Private _Name As String = String.Empty
Private _Other As Integer = 0

Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal Value As String)
_Name = Value
End Set
End Property

Public Property Other() As Integer
Get
Return _Other
End Get
Set(ByVal Value As Integer)
_Other = Value
End Set
End Property

Public Sub New()
'xml serialization has trouble if there is no default constructor
End Sub

Public Sub New(ByVal name As String, ByVal other As Integer)
_Name = name
_Other = other
End Sub

End Class

'the code to test it
Dim test As New Tester("Test1", 6)

'delete old file if found
If IO.File.Exists("data.dat") Then IO.File.Delete("data.dat")
'make the file and stream
Dim fs As New IO.FileStream("data.dat", IO.FileMode.CreateNew)
'serialize it to binary data
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(fs, test)
fs.Close()

'open file again
fs = New IO.FileStream("data.dat", IO.FileMode.Open)
'now deserialize and display data to make sure it worked
Dim retTest As Tester = bf.Deserialize(fs)
fs.Close()
MsgBox(String.Concat("Name:", retTest.Name, " Other:", retTest.Other), , "Binary")

'now here is the samething but to xml

'delete old file if found
If IO.File.Exists("data.xml") Then IO.File.Delete("data.xml")
'make the file and stream
fs = New IO.FileStream("data.xml", IO.FileMode.CreateNew)
'serialize it to xml data
Dim xf As New Xml.Serialization.XmlSerializer(GetType(Tester))
xf.Serialize(fs, retTest)
fs.Close()

'open file again
fs = New IO.FileStream("data.xml", IO.FileMode.Open)
'now deserialize and display data to make sure it worked
Dim xmlTest As Tester = xf.Deserialize(fs)
fs.Close()
MsgBox(String.Concat("Name:", xmlTest.Name, " Other:", xmlTest.Other), , "XML")


Then afterwards you are left with 2 files data.data with the contents and data.xml with the xml contents.

Hinder
Jan 12th, 2003, 01:34 AM
Very nice, I'll have to put this to use, thank you :)