So far you've seen how to save simple data types to a file, and read them back. Most applications don't store their data in simple variables. Instead, they use complicated structures to store their data, such as arrays, ArrayLists, HashTables and so on. It's possible to store an entire array to a file with a process called serialization
. To do that, you convert the array values to a sequence of bytes, which you can then store to a file. The opposite process is called deserialization
Serialization is a big topic in .NET, but here's the basic information you need.. To save an object to file and read it back, you use the Serialize
methods of the BinaryFormatter class. First, import the System.RunTime.Serialization.Formatters namespace into your project to avoid typing excessively long statements. The Formatters namespace contains the BinaryFormatter class, which knows how to serialize basic data types in binary format. Create an instance of the BinaryFormatter class and then call its Serialize
method, passing two arguments: a writeable FileStream instance for the file where you want to store the serialized object, and the object itself:
Dim BinFormatter As New Binary.BinaryFormatter()
Dim R As New Rectangle(10, 20, 100, 200)
method of the BinaryFormatter class accepts a single argumenta FileStream instancedeserializes the object at the current position in the FileStream and returns it as an object. You usually cast the deserialized object to the proper type with the CType function. For example, the following statement returns the serialized Rectangle object saved in the preceding code snippet:
Dim R As New Rectangle()
R = CType(BinFormatter.Deserialize(FS), Rectangle)
You can also persist objects in text format using the XmlFormatter object. To do so, add a reference to the System.Runtime.Serialization.Formatters.Soap namespace with the Project> Add Reference command. After doing that, you can create an instance of the SoapFormatter object, which exposes the same methods as the BinaryFormatter object, but serializes objects in XML format. The following statements serialize a Rectangle object in XML format:
Dim FS As New IO.FileStream("c:\Rect.xml", IO.FileMode.Create, IO.FileAccess.Write)
Dim XMLFormatter As New SoapFormatter()
Dim R As New Rectangle(8, 8, 299, 499)
Double-click the file in which the Rectangle object was persisted to open it with Internet Explorer, as shown in Figure 1.
The examples you've just seen persist and reinstantiate a Rectanglea built-in framework object, but the sequence of commands to persist and reinstantiate custom objects is almost identical. See the Persisting Objects section in the examples at the end of this article for an example.