Click here to Skip to main content
15,897,704 members
Articles / Programming Languages / C#

Hashtable becomes serialized

Rate me:
Please Sign up or sign in to vote.
3.10/5 (16 votes)
21 Oct 20023 min read 108.7K   1K   34  
How to create a hashtable, use it, and serialize/deserialize it.
using System;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Hashtable_Serialized
{
	//Two structs are represented here, we save them both in the hashtable
	//note that each struct attributed as serializable, which means we can serialize the exact
	//data form (struct) into a serialize stream
	[Serializable]
	struct name
	{
		public string forname;
		public string familyname;
	}

	[Serializable]
	struct address
	{
		public string street;
		public int number;
	}
   
	//this is the main class for manipulating the hashtable
	class clsDataBlock
	{
		//this is our hashtable variable, a global one.
		public static Hashtable       NameToAddress = new Hashtable ();   

		[STAThread]
		static void Main(string[] args)
		{
			clsDataBlock db=new clsDataBlock ();
			string ans=""; //answer string
			while("x" != ans) //here we write a menu to the console
			{
				System.Console.WriteLine ("1 to enter new");
				System.Console.WriteLine ("2 to search");
				System.Console.WriteLine ("3 to save (serialize)");
				System.Console.WriteLine ("4 to load (deserialize)");
				System.Console.WriteLine ("5 to show data");
				System.Console.WriteLine ("x to quit");
				System.Console.WriteLine ("-----------------------");
				ans = System.Console.ReadLine (); //and real the selection
			switch(ans)
				{
					//we call the wanted function here
					case "1":db.AddNew();
						break;
					case "2":db.Search();
						break;
					case "3":db.Save();
						break;
					case "4":db.Load();
						break;
					case "5":db.Show();
						break;
				}
			}
		}

		//A method to add new object to the hashtable,
		//we create a struct of name and address, fill it and save it in hash
		public void AddNew()
		{
			name nm; //name struct
			address ad; //address struct
			string ans; //answer string

			//we then ask info from the user and insert that info to our structs
			System.Console.WriteLine ("enter first name (x to exit):");
			ans = System.Console.ReadLine();
			nm.forname = ans;
			System.Console.WriteLine ("enter last name (x to exit):");
			ans = System.Console.ReadLine();
			nm.familyname = ans;
 			System.Console.WriteLine ("enter street name (x to exit):");
			ans = System.Console.ReadLine();
			ad.street = ans;
			System.Console.WriteLine ("enter street number (x to exit):");
			ans = System.Console.ReadLine();
			ad.number = int.Parse (ans);

			//now we save the new object into the hashtable, the key here is the name struct
			NameToAddress.Add(nm,ad);
		}

		//this method asks for the key struct, which is the name, and searches the hashtable
		public void Search()
		{
			name nm2;
			string ans2;
			System.Console.WriteLine ("enter first name:");
			ans2 = System.Console.ReadLine ();
			nm2.forname = ans2;
			System.Console.WriteLine ("enter last name:");
			ans2 = System.Console.ReadLine ();
			nm2.familyname  = ans2;
			System.Console.WriteLine ("working...");

			//here we ask for the struct from the hashtable, given the name object
			object sname = NameToAddress[nm2];
			if (sname != null)
			{
				address ad2 = (address)sname;
				System.Console.WriteLine(" address: "+ ad2.street + " " + ad2.number );
			}
			//none found
			else System.Console.WriteLine ("no name like that...");
		}


		//this method serialize the hashtable into a binary file, 
		//we have a load function to load that exact saved file
		public void Save()
		{
			//file stream states the saved binary
			FileStream fs = new FileStream ("Store.dat",FileMode.OpenOrCreate ,FileAccess.Write );
			try
			{
				Hashtable a = new Hashtable();
				a = NameToAddress;
				BinaryFormatter bf=new BinaryFormatter ();
				//as easy as 1,2,3...we serialize a to a binary formating using file stream.
				bf.Serialize (fs,a );
			}
			finally
			{
				fs.Close ();
			}
		}

		//A method to load saved binary file
		public void Load()
		{
			FileStream fs = new FileStream ("Store.dat",FileMode.Open ,FileAccess.Read );

			try
			{
				Hashtable a = new Hashtable();
				BinaryFormatter bf=new BinaryFormatter ();

				//here we deserialize the binary to a hashtable
				a=(Hashtable)bf.Deserialize (fs);
				NameToAddress = a;
			}
			finally
			{
				fs.Close ();
			}
		}

		//A method to iterate around all values in hashtable and print them
		public void Show()
		{
			name nm3;
			address ad3;

			//for each is used in Dictionary entry 
			foreach (DictionaryEntry entry in NameToAddress )
			{
				nm3 = (name)entry.Key;
				ad3 = (address)entry.Value;
				Console.WriteLine ("name= {0} {1}, address= {2} {3}", nm3.forname,nm3.familyname ,ad3.street ,ad3.number);
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Europe Europe
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions