For those who might be interested, saving a collection (or list) of a custom class turned out to be painfully easy!
Thanks to AtmaWeapon for a push in the right direction (by giving me the "Serializable" keyword to research.)
In my case I have a plotting application that saves graphic objects as custom "Unit" classes. The instances of the unit class are stored in a collection (although a list could also be used) called "units".
A simplified example of my custom class now looks like this:
Code:
<Serializable()> _
Public Class Cls_Unit
<NonSerialized()> _
Public MyPath As GraphicsPath
Public Name As String = Nothing
Public Type As String = Nothing
Public ObjtName As String = Nothing
Public Selected As Boolean = False
End Class
Notice above I had to configure my class for serialization by adding the Serializable attribute. Also worth noting, if you have a property in your custom class that is typed as another custom class, that child class also has to be marked as Serializable. If you fail to configure any related objects as Serializable, you'll get a SerializationException error at runtime. And it will point out to you specifically which objects are not properly marked.
In my case above I was getting an error on the GraphicsPath object. Since I generate that path with a draw method anyway, it wasn't necessary to save it, so I just marked that object "NonSerialized" and the BinaryFormatter now has no issues with it.
Now in my app, as I plot a new unit, the unit is stored in a collection called "units". The collection of units is what defines the resulting graphic plot.
To save the plot as a binary file the code is really very simple:
Code:
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
Sub Write_BinFile()
Dim binFormat As BinaryFormatter = New BinaryFormatter()
Dim fStream As Stream = New FileStream("SaveData.dat", FileMode.Create, FileAccess.Write, FileShare.None)
binFormat.Serialize(fStream, Units)
fStream.Close()
End Sub
Then to re-load my Units collection from the saved bin file:
Code:
Sub Read_BinFile()
Dim fstream As Stream = File.OpenRead("SaveData.dat")
Dim binFormat As BinaryFormatter = New BinaryFormatter()
Units = binFormat.Deserialize(fstream)
fstream.Close()
End Sub
I have to admit, I was actually a little dumbfounded to learn how simple a task this turned out to be!