C# - Saving Settings using serialization

10. March 2011 18:50

Almost every windows program that is written for windows at some stage needs to save some settings ... Somewhere. Some method are better that others depending on what needs to be be saved. Here is a method todo that by serializing an entire class and saving it in the user app data folder on their computer.

 

It does not require much to enable this sort of functionality. Though it can be far superior to the existing set that exists by default in visual studio as it allows you to save an active data state for example and then when the program restarts it's possible to continue from where you left off.

 

You will need the following two functions. These are static so you can place them in any suitable class in your project.

 

 

public static void Serialze(object obj, FileStream Stream)
{
    BinaryFormatter bin = new BinaryFormatter();
    bin.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;
    bin.Serialize(Stream, obj);
}


public static object DeSerialize(FileStream Stream)
{
    BinaryFormatter bin = new BinaryFormatter();
    bin.FilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;
    object x = bin.Deserialize(Stream);
    return x;
}

 

 

With the above function's its now very easy to save the state of a class so long as the class has been tagged with an attribute of "Serializable". Here is a short example of that which i use to store a database connection string structure.

 

 

[Serializable]
internal class Config {
    public string Name = string.Empty;
    public string AuthMode = "Windows Authentication";
    public string Username = string.Empty;
    public string Password = string.Empty;
    public bool RememberPassword = false;
    public string Database = "<default>";

    public Config()
    {

    }

    public Config(string Name)
    {
        this.Name = Name;
    }

    public override string ToString()
    {
        return Name;
    }
}

 

With the above i can then store these as an array of serialized object in a data file on the person's computer.

An example of saving

 

FileStream S = new FileStream(FileName, FileMode.CreateNew, FileAccess.Write, FileShare.None, 8192);

for (int i = 0; i < cboName.Items.Count; i++)
{
    if (cboName.Items[i].GetType() == typeof(Config))
        SUtility.Serialze(cboName.Items[i], S);
}

S.Close();
S.Dispose();

 

And here is an example of loading them again when the program starts.

 

 

FileStream S = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);

Config tmp = null;
do
{
    tmp = (Config)SUtility.DeSerialize(S);
    cboName.Items.Add(tmp);
} while (tmp != null);

S.Close();
S.Dispose();

 

E-mail Kick it! DZone it! del.icio.us Permalink