Save / Restore Application Settings using File

This Simple Class will allow you to Save and restore any class instance using files.

It’s very useful if you want to save your Application settings, Specially if your Application is portable, Or if you do want to use Windows registry.

The Class Code :

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;

public class Settings
{
/// <summary>
/// Read Settings
/// </summary>
/// <param name="ConfigFile">Filename and path to create open Config File and restore Settings</param>
/// <param name="Class">Instance of the Class to Save</param>
/// <returns></returns>
public static bool ReadSettings(string ConfigFile, object Class)
{
    if (!File.Exists(ConfigFile))
       return false;
    using (Stream StreamFile = File.Open(ConfigFile, FileMode.Open))
    {
        BinaryFormatter binformat = new BinaryFormatter();
        foreach (PropertyInfo prop in Class.GetType().GetProperties())
        {
           object objValue = binformat.Deserialize(StreamFile);
           prop.SetValue(Class, objValue, null);
        }

        StreamFile.Close();
    }
    return true;
}

/// <summary>
/// Save Settings
/// </summary>
/// <param name="ConfigFile">Filename and path to create new Config File and store Settings</param>
/// <param name="Class">Instance of the Class to Save</param>
/// <returns></returns>
public static void SaveSettings(string ConfigFile, object Class)
{
    if (File.Exists(ConfigFile))
       File.Delete(ConfigFile);

    using (Stream StreamFile = File.Open(ConfigFile, FileMode.CreateNew))
    {
       BinaryFormatter binformat = new BinaryFormatter();

       foreach (PropertyInfo prop in Class.GetType().GetProperties())
       {
          binformat.Serialize(StreamFile, prop.GetValue(Class, null));
       }
       StreamFile.Close();
    }
  }
}

How to Use :

using System;

class Program
{
   static void Main(string[] args)
   {
      Person p = new Person();
      p.id = 2;
      p.name = "Some Name";

      Settings.SaveSettings("c:\\a.txt", p);

      Person p1 = new Person();
      Settings.ReadSettings("c:\\a.txt", p1);

      Console.WriteLine(p1.id);
      Console.WriteLine(p1.name);
   }
}

public class Person
{
   // IMPORTANT!
   // The Class must contain properties "{get; set;}" NOT Fields or the code will not work.
   public int id { get; set; } 
   public string name { get; set; }
}

Comments

  1. Really great post! I am impressed by the work you are doing here, it is always a pleasure to read your posts. Informative and interesting material, thanks a lot for sharing it with us.

  2. Thank you! This was the perfect solution for saving and restoring configuration settings for my program. Very appreciated!!

Leave a Reply

Your email address will not be published.