Search this blog

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

Search the blog

Loading

Monday, May 24, 2010

How to serialize and de-serialize simple objects part 2

Refining the previous example to include reading from a file, displaying to the console, serializing and de-serializing the objects. This program must showcase the usage of streamreader,streamwriter,binaryformatter,filestream etc

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)
{
Console.WriteLine("Please enter the text to write to the file");
string s1 = Console.ReadLine();

FileStream fs = new FileStream(@"C:\Test.Sam", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, s1);
fs.Close();
Console.WriteLine("Successfully wrote text to file press any key to Read the text from the file");
// Console.ReadKey();
Console.Clear();

FileStream fs2 = new FileStream(@"C:\Test.Sam", FileMode.Open);
BinaryFormatter bf2 = new BinaryFormatter();
string s2 = (string)bf2.Deserialize(fs2);
fs2.Close();
StreamReader sr = new StreamReader(@"C:\Test.Sam");
string TextEntered = "";
string temp = "";
if ((temp = sr.ReadLine()) != null)
{
TextEntered = temp + sr.ReadLine();

}
Console.WriteLine("Reading the contents of the file ...Press any key");
Console.ReadKey();
Console.WriteLine(TextEntered);
Console.WriteLine("Deselerializing the contents from the file...");
Console.WriteLine(s2);
Console.ReadKey();
sr.Close();






}
}
}

Incase you find anything confusing, contact me

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

No comments:

Post a Comment