Skip to content

Instantly share code, notes, and snippets.

@devmnj
Created June 5, 2020 17:45
Show Gist options
  • Select an option

  • Save devmnj/85a4047953e1fa3d39d6b197e763626e to your computer and use it in GitHub Desktop.

Select an option

Save devmnj/85a4047953e1fa3d39d6b197e763626e to your computer and use it in GitHub Desktop.
Serialize Helper class for encrypt and serialize any object collection in C#
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");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment