C# – Saving a C# object to a file

cclassobjectsaveserialization

I'm to implement a new member application without the use of databases. I'm planning to create a class to define each member, with fields defining name, department etc. I wish to save a list of these members into a file (not plain text). So my question is to how to save a class object into a file ?

Thanks in advance 🙂

Best Answer

I would suggest doing JSON or XML serialization and then encrypting the contents with some algorithm. I wouldn't go with binary serialization because it's not very friendly when you need to change the assembly version.

I am using the following code together with Newtonsoft.Json (you can get it on NuGet) to accomplish this:

using System.IO;
using System.Security.Cryptography;
using System.Text;

using Newtonsoft.Json;

class SecureJsonSerializer<T>
    where T : class
{
    private readonly string filePath;

    private readonly ICryptoTransform encryptor;

    private readonly ICryptoTransform decryptor;

    private const string Password = "some password";

    private static readonly byte[] passwordBytes = Encoding.ASCII.GetBytes(Password);

    public SecureJsonSerializer(string filePath)
    {
        this.filePath = filePath;
        var rmCrypto = GetAlgorithm();
        this.encryptor = rmCrypto.CreateEncryptor();
        this.decryptor = rmCrypto.CreateDecryptor();
    }

    private static RijndaelManaged GetAlgorithm()
    {
        var algorithm = new RijndaelManaged();
        int bytesForKey = algorithm.KeySize / 8;
        int bytesForIV = algorithm.BlockSize / 8;
        algorithm.Key = key.GetBytes(bytesForKey);
        algorithm.IV = key.GetBytes(bytesForIV);
        return algorithm;
    }

    public void Save(T obj)
    {
        using (var writer = new StreamWriter(new CryptoStream(File.Create(this.filePath), this.encryptor, CryptoStreamMode.Write)))
        {
            writer.Write(JsonConvert.SerializeObject(obj));
        }
    }

    public T Load()
    {
        using (var reader = new StreamReader(new CryptoStream(File.OpenRead(this.filePath), this.decryptor, CryptoStreamMode.Read)))
        {
            return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
        }
    }
}