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) has been around computers since the 1980's when the first affordable home computers came on the market. His journey from that very first Dragon 32 to the present has taken him through many different facets of the IT Industry. These include formal training as a Systems Analyst, employment in a mainframe software development environment, and a short time spent demonstrating rugged military IT systems in the days when it took two strong men to carry a 'mobile' system.

His most rewarding challenge was the creation of a financial management system for a large organisation.

Now based in an idyllic lochside location in the West of Scotland, he is currently involved in a range of development projects, whenever he can drag his gaze away from the stunning surrounding views, that is!

Ged is a Microsoft MVP, Senior Editor for DevCity.NET, vbCity Developer Community Leader and Admin, Helper of the Month competition winner and DevCity.NET newsletter Editor.

 

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

   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.Clear()
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))
Next

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.

Summary
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:4.87499999999998 out of 5
 32 people have rated this page
Article Score7876
Related Articles
Attachments
Comments    Submit Comment

Comment #1  (Posted by Adam D. on 03/22/2007)
Rating
Excellent article Ged, much appreciated.
 
Comment #2  (Posted by an unknown user on 03/23/2007)
Rating
Cool!
 
Comment #3  (Posted by an unknown user on 03/28/2007)
Rating
Well done helped me get a grasp of VB.NET 2006
 
Comment #4  (Posted by an unknown user on 05/09/2007)
Rating
The explanations are adequate and the code is very clearly exposed. The code works neatly.
 
Comment #5  (Posted by mike holman on 05/09/2007)
Rating
this has proven to be a WONDERFUL application to learn from. very well explained, and i've been customizing this application to learn even more.

picking apart the code, line by line, has taught me a great deal. it's not too complex of an application, nor is it too simple. being an absolute beginner in vb.net, this site is a godsend, and it's great to have experienced programmers take the time to create tutorials like this.

thanks!!!!!
 
Comment #6  (Posted by an unknown user on 05/25/2007)
Rating
its good
 
Comment #7  (Posted by an unknown user on 06/04/2007)
Rating
Another excellent article from Ged.
He just gets the things across very much entertaining.
This guy is good !
Wonder if he is up to write a book.
 
Comment #8  (Posted by an unknown user on 07/08/2007)
Rating
Excellent. I really learned a lot from this. Keep up the good work
 
Comment #9  (Posted by an unknown user on 07/08/2007)
Rating
Excellent. I really learned a lot from this. Keep up the good work
 
Comment #10  (Posted by an unknown user on 08/10/2007)
Rating
Great, easy and comprehensive, summarization of important techniques.

Thanks a lot!
 
Comment #11  (Posted by an unknown user on 08/17/2007)
Rating
Not counting 'Hello, World!' this was my first experience with VB anything. The tutorial was well thought out and implemented. The variety topics was enough to keep my interest with out becoming over whelming.

Thank a Bazillion
 
Comment #12  (Posted by an unknown user on 08/20/2007)
Rating
Been Programming for a few years now and this is the best artical I have ran accross. I wasnt sure how they used the new generic class type for VB2005. Nice Work.
 
Comment #13  (Posted by an unknown user on 08/27/2007)
Rating
Thank you!

I have been playing with vb.net for a while and have tried following several tutorials trying to make a high score board for tetris as a learning project. I got frustrated, however, as they were all explained poorly and I struggled to follow them.

This article is very clear and well explained and I actually understand writing to and reading from binary files now. Thank you very much.
 
Comment #14  (Posted by an unknown user on 11/08/2007)
Rating
was a fun guide to recreate thnx for your time and effort Ged.
 
Comment #15  (Posted by an unknown user on 11/08/2007)
Rating
was a fun guide to recreate thnx for your time and effort Ged.
 
Comment #16  (Posted by an unknown user on 12/19/2007)
Rating
it's good pice of work about write file and read file again excellent

thanks for this article

 
Comment #17  (Posted by an unknown user on 01/23/2008)
Rating
Great stuff. Easy to understand and use even for a meathead like me. It would be wonderfull if you expanded this article to include more functions like edit, remove and delete all. Many thanks

Bob
 
Comment #18  (Posted by an unknown user on 01/25/2008)
Rating
Easy to understand.
 
Comment #19  (Posted by Clint on 04/17/2008)
Rating
Please excuse me. I've very new at .NET. When I create my form and enter the code "Dim Player1 As New Player(TextBox1.Text, CInt(TextBox2.Text))
Label3.Text = String.Format("Player Name: {0} {1}Current Score: {2}", Player1.Name,
ControlChars.CrLf, Player1.Score.ToString)" as the click event I get an error saying that label3 is not declared. How do I fix this?
 
Sponsored Links