Serialization is the process of storing objects / user defines classes into a disc files. It stores state of the object i.e. member variable values to disk. Deserialization is reverse of serialization i.e. it’s a process of reading objects from a file where they have been stored.
As you know encryption is to hide information from others .Encryption and decryption operations require a special key. Think of a key as a password for the encryption and decryption operations
Serialization and encryption
My Serialize Helper class assist you to serialize any object or object collection to binary data file and also it encrypt data using DESCryptoServiceProvider class. Using the BinaryFormatter we can serialize objects and save into a file. Like wise we can reverse the process too.
Helper class
Our Helper class has following functions
- public static void SerialiZe<T>(string path)
- public static T DeserialiZe<T>(string path)
public static class SerializeHelper | |
{ | |
static byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; | |
static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; | |
static DESCryptoServiceProvider des = new DESCryptoServiceProvider(); | |
public static void SerialiZe<T>(T data, string path) | |
{ | |
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write)) | |
using (var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write)) | |
{ | |
BinaryFormatter formatter = new BinaryFormatter(); | |
// This is where you serialize the class | |
formatter.Serialize(cryptoStream, data); | |
} | |
} | |
public static T DeserialiZe<T>(string path) | |
{ | |
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) | |
using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read)) | |
{ | |
BinaryFormatter formatter = new BinaryFormatter(); | |
var deserialized = (T)formatter.Deserialize(cryptoStream); | |
return deserialized; | |
} | |
} | |
} | |
//usage | |
ObservableCollection<CustomClass> obList = new ObservableCollection<CustomClass>(); | |
CustomClass obj= new CustomClass(); | |
obj=new CustomClass(Value); | |
obList.Add(obj); | |
//Serialize | |
SerializeHelper.SerialiZe<ObservableCollection<<CustomClass>>(obList, @"data.pk"); | |
//deserialize | |
var List = SerializeHelper.DeserialiZe<ObservableCollection<PackageClass>>(@"data.pk"); | |
As you note that , we are using generic parameter which is an arbitrary type of T. You can use any custom class/ type in place of T.
Generic type offers better performance and re-usability
How to use
Make use of the Helper class , add it to your project and just use the static class method.
that’s it