Saving User Preferences and Settings within your C# Application

Written by on Sunday 15th May 2011 under C#

Microsoft .Net provides a powerful method for storing and retrieving user settings - something almost every application will at some stage need to do. This article will show you how to quickly and easily save settings to the Registry, to a SQL Database or to an XML file.

Saving and loading user settings was formerly done using the trusty old INI configuration file, and more recently using the system Registry. While these two methods are perfectly valid, a more structured and scalable method is to use the .Net provided tools.

The first thing you need is a class that holds all the data you need to save, in this example we are creating a simple class called UserPreferences which contains two strings and an integer.

public class UserPreferences
{
    internal string _DisplayName;
    public string DisplayName
    {
        get { return _DisplayName; }
        set { _DisplayName = value; }
    }
 
    internal string _Company;
    public string Company
    {
        get { return _Company; }
        set { _Company = value; }
    }
 
    internal int _SomeValue;
    public int SomeValue
    {
        get { return _SomeValue; }
        set { _SomeValue = value; }
    }
}

This class will form a basis for each of the derived classes that we will use for storing the information in XML, Registry and Database.

XML Serialization

We have already seen XML Serialization in a previous tutorial, so I will keep this section short.

The first thing to do is mark the class as Serializable by inserting the [Serializable] attribute before the declaration or create a class that implements the ISerializable interface.

To save the user preferences class to an XML file simply create an XML Writer and invoke the Serialize method.

UserPreferences up = new UserPreferences();
 
XmlSerializer mySerializer = new XmlSerializer(typeof(UserPreferences));
StreamWriter myWriter = new StreamWriter("c:/prefs.xml");
mySerializer.Serialize(myWriter, up);
myWriter.Close();

To read the data back in, you simply call the Deserialize method.

UserPreferences up;
 
XmlSerializer mySerializer = new XmlSerializer(typeof(UserPreferences));
FileStream myFileStream = new FileStream("c:/prefs.xml",FileMode.Open);
 
up = (myTestClass)mySerializer.Deserialize(myFileStream);

You could also implement the IFormatter interface which will allow you to format the data and save it within a SOAP XML package using SoapFormatter or using a BinaryFormatter to store the data in a binary format.

Saving Settings within a SQL Database

If you are developing an application that relies on data stored within a database (i.e. the program will not function without the database) then it makes sense to store configuration settings for the application within the database as well. This allows for a distributed model where the application can be downloaded to any client machine and settings retrieved from a central source.

We need to create an implementation of the class that will handle saving to the database. I am going to create a derived class which inherits the properties of UserPreferences as well as two new methods; one for saving to the database and one for loading the data back. Since we need to load the data each time the program is run (when we instantiate the UserPrefererences class) we can put the loading code into the constructor for the class.

You will need to add 'using System.Data.SqlClient;' to your references.

public class SQLUserPreferences : UserPreferences
{
    public SQLUserPreferences()
    {
        string connectionString = "Data Source=.SQLEXPRESS;AttachDbFilename="C:DOCUMENTS AND SETTINGSTROTTTMY DOCUMENTSVISUAL STUDIO 2005PROJECTSWINDOWSAPPLICATION5WINDOWSAPPLICATION5DATABASE1.MDF";Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlConnection sqlCon = new SqlConnection(connectionString);
 
        sqlCon.Open();
        string commandString = "SELECT * FROM appSettings WHERE UserLogon = '" +
        System.Environment.UserDomainName + "" +
        System.Environment.UserName.ToString() + "'";
 
        SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
        SqlDataReader dr = sqlCmd.ExecuteReader();
 
        while (dr.Read())
        {
            // Index 0 contains the domain/username used 
            // as a primary key for the database.
            _DisplayName = dr.GetString(1);
            _Company = dr.GetString(2);
            _SomeValue = dr.GetInt32(3);
        }
 
        dr.Close();
        sqlCon.Close();
    }
 
    public void Save()
    {
        string connectionString = "Data Source=localhost; Integrated Security=SSPI; Initial Catalog=appSettings";
        SqlConnection sqlCon = new SqlConnection(connectionString);
 
        sqlCon.Open();
        string commandString = "UPDATE appSettings SET " +
          "DisplayName = '" + _DisplayName + "', " +
          "Company = '" + _Company + "', " +
          "SomeValue = " + _SomeValue +
          " WHERE UserLogon = '" +
          System.Environment.UserDomainName + "//" +
          System.Environment.UserName + "'";
 
        SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
        sqlCmd.ExecuteNonQuery();
        sqlCon.Close();
    }
}

Saving Settings to the Registry

The Windows registry is a general purpose mechanism for storing information that is to be maintained when a Windows application terminates. The .Net framework provides a class that provides easy access to registry methods. The registry contains many locations, called keys, such as HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER. These are a few of the read only base keys that contain information about users, the operating system, the software installed and the settings for the current logged on user.

We are going to create a similar derived class to the one we created for SQL Databases; in fact the technique is exactly the same. You will need to add a reference to the namespace Microsoft.Win32.

You will need to add 'using Microsoft.Win32;' to your references.

public class RegUserPreferences : UserPreferences
{
    public RegUserPreferences()
    {
        RegistryKey UserPrefs = Registry.CurrentUser.OpenSubKey("SOFTWAREYour-Company-NameApp-Name", true);
 
        if (UserPrefs != null)
        {
            _DisplayName = UserPrefs.GetValue("DisplayName").ToString();
            _Company = UserPrefs.GetValue("Company").ToString();
            _SomeValue = int.Parse(UserPrefs.GetValue("SomeValue").ToString());
        }
        else
        {
            // Key did not exist so use defaults
            _DisplayName = System.Environment.UserName;
            _Company = System.Environment.UserDomainName;
            _SomeValue = 0;
        }
    }
 
    public void Save()
    {
        RegistryKey UserPrefs = Registry.CurrentUser.OpenSubKey("SOFTWAREYour-Company-NameApp-Name", true);
 
        if (UserPrefs == null)
        {
            // Value does not already exist so create it
            RegistryKey newKey = Registry.CurrentUser.OpenSubKey("SOFTWAREYour-Company-Name", true);
            UserPrefs = newKey.CreateSubKey("App-Name");
        }
 
        UserPrefs.SetValue("DisplayName", _DisplayName);
        UserPrefs.SetValue("Company", _Company);
        UserPrefs.SetValue("SomeValue", _SomeValue);
    }
}

More Tutorials in Windows Forms Applications

  1. Basics of C# Windows Forms Applications
  2. Menus, Popups and Toolbars in .Net Forms and C#
  3. Using Common Dialogue Boxes in C#
  4. Using Multiple Forms in C#
  5. List Boxes and Tree Views in C#
  6. List Box Data Binding
  7. Using Multiple Forms in C# Applications with MDI
  8. Creating Controls for Windows Forms and C#
  9. Saving User Preferences and Settings ⇦ You Are here

One Response to “Saving User Preferences and Settings within your C# Application”

  1. You saved a lot of time and stress. I was in a hurry and could not find any solution. Built-in settings were not being persistent even after all tries and save() etc. Registery was not a go because Click Once dont support admin rights and hence I can not publish my app.

    You are awesome.

Leave a Reply