1. Computing

Simple File Processing and VB.NET

Serializing to files

From , former About.com Guide

Another thing my friend wanted to do was ...

... something that I do quite frequently in VB6 ... I declare a Type (Structure in VB.NET), and then instantiate the type with

Dim X as TypeX

and then do

Open <filename> for random as #1 Len=X

which allows me to read and write instances of the Type.

Coming right up! There are several ways to do this, but one way would be to use serialization.

In brief, serialization is the process of converting an object into a linear sequence of bytes called a "byte stream" that can then be saved in a file. Deserialization just reverses the process. But why would you want to convert an object into a byte stream?

The reason is so you can move the object around. Consider the possibilities. Since "everything is an object" in .NET, you can serialize anything and save it to a file. So you could serialize pictures, data files, the current state of a program module ('state' is like a snapshot of your program at a point in time so you could temporarily suspend execution and start again later) ... whatever your system is doing.

You can also store these objects on disk, send them over the web, pass them to a different program, keep a backup copy for safety or security. The possibilities are quite literally endless.

To demonstrate how to use serialization, let's go back to the Win.Ini file to test with. In this example, the data is not only serialized to a file, but the structure of the file is saved too. The structure can be declared in a module to keep things ... well ... structured.

Module Parms
   <Serializable()> Public Class ParmExample
      Public Parm1Name As String
      Public Parm1Value As String
      Public Parm2Name As String
      Public Parm2Value As String
   End Class
End Module

Then, individual values can be saved to a file like this:

Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters

Private Sub SerializeSave_Click( ...
   Dim ParmData As New ParmExample
   ParmData.Parm1Name = "Mail"
   ParmData.Parm1Value = "MAPI=1"
   ParmData.Parm2Name = "MCI Extensions.BAK"
   ParmData.Parm2Value = "m2v=MPEGVideo"
   Dim s As New FileStream("ParmInfo", FileMode.Create)
   Dim f As New BinaryFormatter
   f.Serialize(s, ParmData)
   s.Close()
End Sub

And those same values can be retrieved like this:

Private Sub SerializeRead_Click( ...
   Dim s = New FileStream("ParmInfo", FileMode.Open)
   Dim f As BinaryFormatter = New BinaryFormatter
   Dim RestoredParms As New ParmExample
   RestoredParms = f.Deserialize(s)
   s.Close()
   Console.WriteLine(RestoredParms.Parm1Name)
   Console.WriteLine(RestoredParms.Parm1Value)
   Console.WriteLine(RestoredParms.Parm2Name)
   Console.WriteLine(RestoredParms.Parm2Value)
End Sub

©2013 About.com. All rights reserved.