-
Serialization
It is fairly easy to Serialize objects in Visual Basic.
What is serialization for?
Code:
Public Class Data
Public Shared Sub Save(Path As String, Data As Type)
Dim BF As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Using S As New IO.FileStream(Path, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
BF.Serialize(S, Data)
End Using
End Sub
Public Shared Function Load(Path As String) As Type
Dim BF As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Using S As New IO.FileStream(Path, IO.FileMode.OpenOrCreate, IO.FileAccess.Read)
Try
Return CType(BF.Deserialize(S), Type)
Catch ex As Exception
' File not found/cannot be read.
Return Nothing
End Try
End Using
End Function
End Class
Don't forget to add the serializable attribute on the class you wish to serialize.
Code:
<Serializable()>
Public Class SomeType
' Properties...
End Class
Best of luck,
NinjaNic
-
Re: Serialization
Small tip. You should encourage programmers to propagate the exception instead of returning Nothing when failing to deserialize from a file. I'm sure there is plenty of debate over which pattern is better, but when dealing with files, it's a common practice to let the user know that the file couldn't be read. Of course you can treat a return value of Nothing as failure but it gives no information on why it failed.
-
Re: Serialization
You can read this SO thread if you're interested in the debate concerning returning null vs throwing exceptions.