Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  OOP: Create, Collect, Sort, Save and Retrieve Objects  »  Saving Collections of Objects
 »  Home  »  Visual Studio 2005  »  OOP: Create, Collect, Sort, Save and Retrieve Objects  »  Saving Collections of Objects
 »  Home  »  Windows Development  »  Visual Basic 2005  »  OOP: Create, Collect, Sort, Save and Retrieve Objects  »  Saving Collections of Objects
OOP: Create, Collect, Sort, Save and Retrieve Objects
by Ged Mead | Published  03/18/2007 | .NET Newbie Visual Studio 2005 Visual Basic 2005 | Rating:
Ged Mead

Ged Mead (XTab) is a Microsoft Visual Basic MVP who has been working on computer software and design for more than 25 years. His journey has taken him through many different facets of IT. These include training as a Systems Analyst, working in a mainframe software development environment, creating financial management systems and a short time spent on military laptop systems in the days when it took two strong men to carry a 'mobile' system.

Based in an idyllic lochside location in the West of Scotland, he is currently involved in an ever-widening range of VB.NET, WPF and Silverlight development projects. Now working in a consultancy environment, his passion however still remains helping students and professional developers to take advantage of the ever increasing range of sophisticated tools available to them.

Ged is a regular contributor to forums on vbCity and authors articles for DevCity. He is a moderator on VBCity and the MSDN Tech Forums and spends a lot of time answering technical questions there and in several other VB forum sites. Senior Editor for DevCity.NET, vbCity Developer Community Leader and Admin, and DevCity.NET Newsletter Editor. He has written and continues to tutor a number of free online courses for VB.NET developers.


View all articles by Ged Mead...
Saving Collections of Objects

Saving Collections of Objects

    In many situations where you are dealing with collections of objects, you find sooner or later that you need some way of storing (or persisting) the data, usually to and from a file on the hard drive.  

 You have probably already had some experience of writing to files and reading back from them using some of the many and varied  basic System.IO methods that are available.   These are excellent when you want to save blocks of text, for instance, and read them back when needed.   But when it comes to saving collections of custom objects, such as the Player objects we are dealing with in this article, there are better ways.

   So, although it is perfectly possible to write and read the data needed to store Player objects, including the values assigned to properties for individual instances, it can become long-winded, particularly if the number of properties begins to increase.   What we will look at in this section is using Serialization and Deserialization for the task.


   Serialization is essentially a way of breaking down the data into a series or stream of individual bytes that can then be sent to some repository such as a file on a hard drive.   Serialization and Deserialization sound like quite complex topics (and they can be), but we don't need to dig very deeply into the technology in order to be able to use it for our purposes here.

  The first thing we need to do is to inform the compiler that our class is Serializable.   This is very simply done -  just place the Serializeable Attribute <SERIALIZABLE> in front of the declaration line of the Player Class,  i.e.:

<SERIALIZABLE()>Public Class Player

   Now we can write code that will serialize individual Player instances or - more usefully - collections of them, to a file.  For the purposes of this article I am going to hard-code the file path and also write procedures that are specific for our Player Class.   Just bear in mind that for longer term use it is very easy to use the same general approach to write generic procedures that can be used for other kinds of class objects.

  Firstly you will need to add two more Imports statements to the form file:

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

   Also it will be helpful to have a variable to hold the path and name of the file that we plan to read to and write from.  Because this variable will need to be accessed from more than one separate procedure (e.g. one that reads from file and one that writes) this variable should be placed near the the top of the form code, outside any procedures:

Dim DataFile As String = Application.StartupPath & "\PlayerData.BIN"

 Next you need the following code which you can place, for example, in a Button Click event on the form.

  ' Create a FileStream
Using FStrm As New FileStream(DataFile, FileMode.OpenOrCreate)
  ' A BinaryFormatter
  Dim BinForm As New BinaryFormatter
  ' Serialize the data using the BinaryFormatter
  ' --> FileStream --> File

  BinForm.Serialize(FStrm, PlayersList)
End Using

  The "Using" statement is new to VB 2005 and is a handy shorthand way of ensuring that the filestream is released and disposed as soon as it has done its work.   Prior to VB 2005, this was something you would have handled in code with Close and Dispose instructions.  It isn't strictly necessary in all cases but is worth including in your code whenever you are working with Streams.



  This code creates a FileStream (which in its simplest terms you can think of as a kind of conduit from your application to the hard drive). The file path and the instruction to open or create that particular file is passed to this FileStream.

  A Binary Formatter is required next in order to "translate" the data (Serialize it ) in binary form to pass it via theFileStream to the hard drive storage. As you can see, the name of the FileStream and the source data - the list of Players - is passed to the Binary Formatter.

  In the demonstration project I have cleared all the data from PlayersList as the next step. This is probably not something you would usually do, but I've done that in the demo so that you can easily test that the next stage - that is reading data back from the file - works properly.

Deserializing Data From The File
  The reverse process, i.e. getting data back from the file and storing it in the PlayersList is broadly similar.  Here is the code (which you may want to put in the click event of another button):

' Create a FileStream
Using FStrm As New FileStream(DataFile, FileMode.Open)
Dim BinForm As New BinaryFormatter
' Deserialize the data using the BinaryFormatter
PlayersList = DirectCast(BinForm.Deserialize(FStrm), List(Of Player))
End Using

' Redisplay the data from file
ListBox1.Items.Add("Data received from file:- ")

For Each APlayer As Player In PlayersList
 ListBox1.Items.Add(String.Format("{0}, Current Score: {1}", APlayer.Name, APlayer.Score.ToString))

How It Works
The FileStream creation process is more or less the same as that we have used previously. For obvious reasons though, the FileMode used is FileMode.Open as we need to access a currently existing file and not create a new empty one.
(Just as a side note, you'll see that the demo solution also includes a check that the file does actually exist - always a wise precaution. )

  The BinaryFormatter this time Deserializes the data. The rather complicated looking line:-
PlayersList = DirectCast(BinForm.Deserialize(FStrm), List(Of Player))
  feeds the data directly into PlayersList.   So essentially that line is saying "Fill the PlayersList by deserializing everything you find via the FileStream, turning it into the format that the Player Class uses."

The remaining lines simply display the read data in the listbox.

In this article you have seen how to create a class, a collection, sort the collection, save data to a file and read it back in the correct format.   With relatively very few lines of code in total you have some very powerful tools - the last section, Serialization and Deserializaton especially make very easy work of what would otherwise be a complicated and fiddly task.

   You can use this approach in projects of your own and I hope that this article has provided you with a clear explanation of the steps involved, should you wish to do so.   As mentioned earlier, there is a downloadable demonstration Solution, which includes all the code discussed in this article, plus some additional validation and user interface features.

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:3.88372093023255 out of 5
 86 people have rated this page
Article Score27959
Sponsored Links