Search this blog

You can search for all the topics in our blog using our google custom search now.

Search the blog

Loading

Tuesday, May 25, 2010

Creating a serilizable class and Writing it to a file

We have already seen how to serialize simple type objects like string, int etc etc, you must be wondering and asking yourself  "Okay and So what???". Imagine you have a requirement where you need to store the class objects to a file, how would you do that? Thats exactly when you use serialization to store the class objects and de-serilization to retrieve those stored class object.

Am going to create a new console application and to my project on right in the solution explorer, go ahead and add a new item-->Class-->name it as Item.Our class will have two attributes name and price. To make a class serializable you need to include this [serializable]. Our class will have a constructor and a ToString() method which overrides the ToString Method from Object Base Class.

What are you waiting for? go ahead and create a class like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace serilizationexample
{
    [Serializable]
    public class Item
    {
        public string name;
        public double price;
        public Item(string _name, double _price)
        {
            name = _name;
            price = _price;
        }

        public override string ToString()
        {
            return "The Item "+name+" would cost you " + price.ToString();
        }

    }
}

Lets go ahead and write this class object to a file. Open program.cs from console application project, and create a filestream like this:
FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
This tell us that fs opens a file called Test.Sam from given location.To serialize the object we need to create binary formatter as follows:
BinaryFormatter bf = new BinaryFormatter();

Now you need to create an object from Item class like this:
Item ItemObj = new Item("Xbox", 325.00);
Once you have object created, lets serialize it before we can write it to a file
bf.Serialize(fs, ItemObj);
Great!!! Now you have written the object to the given file, go ahead take a look at the file that you created.To do that go to your file location(in my case its C:\), open Test.Sam with notepad. Lets read the file from our program and display it on the console. Create a streamreader object "sr" and read from the file like this:

StreamReader sr = new StreamReader(@"C:\Test.Sam");
            string TextEntered = "";
            string temp = "";
            if ((temp = sr.ReadLine()) != null)
            {
                TextEntered  = temp + sr.ReadLine();
           
            }
Display the contents of the file on screen:
Console.WriteLine(TextEntered);


We are almost done now, go ahead and deserilialize the object from the file like this:
Item ItemRetrieved = (Item) bf2.Deserialize(fs2);
Now you have learned how to serialize and deserialize the class objects.

This is how your program.cs file should look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace serilizationexample
{

    class Program
    {
       
        static void Main(string[] args)
        {
         

            FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            Item ItemObj = new Item("Xbox", 325.00);
            bf.Serialize(fs, ItemObj);
            fs.Close();
            Console.WriteLine("Successfully wrote Obj to file press any key to Read the text from the file");
           
           

           
          
           
           
            StreamReader sr = new StreamReader(@"C:\Test.Sam");
            string TextEntered = "";
            string temp = "";
            if ((temp = sr.ReadLine()) != null)
            {
                TextEntered  = temp + sr.ReadLine();
           
            }
            Console.WriteLine();
            Console.WriteLine("Reading the contents of the file ...Press any key");
            sr.Close();
            Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine(TextEntered);
            FileStream fs2 = new FileStream(@"C:\Test.Sam", FileMode.Open);
            BinaryFormatter bf2 = new BinaryFormatter();
            Console.WriteLine();
            Console.WriteLine("Deselerializing the contents from the file...");
           Item ItemRetrieved = (Item) bf2.Deserialize(fs2);
           string s2 = ItemRetrieved.ToString();
            Console.WriteLine(s2);
            Console.WriteLine();
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            fs2.Close();
           
           


           


        }
    }
}

If you need any help since you are totally new to all of this, then contact me and i will try to help you out.

Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics

No comments:

Post a Comment