r/visualbasic • u/candyforlunch VB.Net Master • Mar 07 '14
For your pleasure: A generic XML serializer + deserializer
I see a lot of posts where people are trying to save/load classes to disk, with varying results. I tend to recommend looking at the XMLSerializer documentation, but they're limited in that they only work for one specific class. Coding the same thing over and over again is always stupid, so a long time ago I made a serializer/deserializer that works with anything you give it! Huzzah!
Load/Deserialize:
Public Function Load(Of T)(path As String, classToLoad As T) As T
' I had a specific reason for doing this, but i don't remember why. maybe it
' was related to not being able to call GetType() on a null object? oh well..
Dim tp = If(classToLoad Is Nothing, GetType(T), classToLoad.GetType())
Dim stream As StreamReader
Try
Dim reader = New XmlSerializer(tp)
stream = New StreamReader(path)
classToLoad = CType(reader.Deserialize(stream), T)
Catch ex As Exception
' write a message to the console, pop up a message box, whatever
classToLoad = Nothing
Finally
If stream IsNot Nothing Then
stream.Close()
End If
End Try
Return classToLoad
End FunctionSave/Serialize:
Public Sub Save(Of T)(path As String, classToSave As T)
Dim writer As New StreamWriter(path)
Try
Dim ser As New XmlSerializer(classToSave.GetType())
ser.Serialize(writer, classToSave)
Catch ex As Exception
' do the needful
Finally
If writer IsNot Nothing Then
writer.Close()
End If
End Try
End SubEdit: Yes, I do know that the Try...Catch blocks are functionally equivalent to Using..., I just like the ability to inform the user of why it failed
6
Upvotes
2
u/Koenigseggissenisegg Mar 07 '14
Man where you you 6 months ago when I needed this. Anyway, through my frustrations, I implemented binary serialization. Smaller, faster files, and no need to specify object type. Drawback is files cannot be edited in notepad like XML.
It is also important to note that serialization is dependent on software build. If you change/update your program, you won't be able to load outdated serialized files. Creating and referencing a separate dll of serialization routines is the way to go.
Binary serialization:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Private Serializer As New BinaryFormatter