Writing a collection to file

After hours of searching the web I have worked out how to do it! Its done by serialization. I have created a class called CollectionSerializer which will read/write any object to disk. To write a object pass it to saveCollection() passing in a fileName String and the object to be written. To read the object call loadCollection and pass in the fileName. This will return the object back. Remember to cast the object to its proper type for it to work. Its very sensible to use FileInfo to check that the file exists before calling the loadCollection function.

Code:
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

This class will allow a collection to read and write information to/from disk
**NOTE All classes used in serialization has to be <Serializabe()>
** When returning a collection it must be casted into the correct type with CTYPE
Public Class CollectionSerializer

    Private serializer As New BinaryFormatter()

    This function will serialize the object that is passed in
    Public Function saveCollection(ByVal fileName As String, ByVal myCollection As Object)
        Save the new data with the Serializer
        Dim myFileStream As Stream = File.Create(Application.StartupPath & "\" & fileName & ".txt")


        serializer.Serialize(myFileStream, myCollection)

        myFileStream.Close()
    End Function

    This function will deserialize and return the object
    Public Function loadCollection(ByVal fileName As String) As Object

        Dim myObject As New Object()
        Dim myFileStream As Stream = File.OpenRead(Application.StartupPath & "\" & fileName & ".txt")


        myObject = serializer.Deserialize(myFileStream)
        myFileStream.Close()

        Return myObject

    End Function

End Class
 
Back
Top