How to Save a hashtable into a file ( Serialization and Deserialization )

Posted by SunKwon Kim on 2008/09/24 16:40
Filed under .NET Framework
Tags : , ,

To save a class or structure in c#, serialization and de-serialization are needed.
Using serialization, we can convert data into a stream. After that, we can save the stream into a file or a database.

User image

The simple code is following.

// we uses BinaryFormatter and FileStream for serializing a double array and connecting it into a file.
// Just create FileStream and Binaryformatter objects and connect with each others.

double[] doubleArrayWillBeSaved = double[100];  // Double array will be saved into a file
BinaryFormatter bf = new BinaryFormatter();  // creates a BinaryFormatter object
FileStream fs = new FileStream("C:\\bin.dat", FileMode.Create); // Creates a FileStream Object which handles file creations.
bf.Serialize(fs, doubleArrayWillBeSaved ); // double array is serialized and saved into a file. BinaryFormatter serializes double array and send it to FileStream. Then Filestream save it into a file, "bin.dat".



Opposite work  is also possible. You can restore data from a stream. We call it "De-serialization". At first, you create a stream from the source (a file, P2P, or a database) and then convert the stream into a object (variable, class object, or something) which you can handle.

User image
 The sample code is following.

// In de-serializing, we uses same classes, BinaryFormatter and FileStream.
// But just call Deserialize function for deserializing.
// If you understand the previous example, this example is easy to understand.
// Deserialize function returns the object which has double array we saved.
// The program doesn't know what it is, but we know. So we teach the program what it is.
// For tell the type of object, we uses type-transforming. In this case, we tell the program this object type is "Double[]"
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream("C:\\bin.dat", FileMode.Open);
Double[] doubleArrayFromAFile = (Doube[]) bf.Deserialize(fs);

For using BinaryFormatter and FileStream, we declare namespaces.
In the first pare of the codes, the following codes exists if you uses Visual Studio.

using System;
using System.Collections.Generic
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

Just adds two lines to the next for using BinaryFormatter and FileStream.
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;



I hope this article will be helpful for you.
Have a good time.
2008/09/24 16:40 2008/09/24 16:40
Trackback URL >> http://crowsley2.cafe24.com/trackback/2
Leave a comment
[Log-ing][What is OpenID?]