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.

  1. publicclass UserPreferences
  2. {
  3.     internalstring _DisplayName;
  4.     publicstring DisplayName
  5.     {
  6.         get{return _DisplayName;}
  7.         set{ _DisplayName =value;}
  8.     }
  10.     internalstring _Company;
  11.     publicstring Company
  12.     {
  13.         get{return _Company;}
  14.         set{ _Company =value;}
  15.     }
  17.     internalint _SomeValue;
  18.     publicint SomeValue
  19.     {
  20.         get{return _SomeValue;}
  21.         set{ _SomeValue =value;}
  22.     }
  23. }

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.

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

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

  1. UserPreferences up;
  3. XmlSerializer mySerializer =new XmlSerializer(typeof(UserPreferences));
  4. FileStream myFileStream =new FileStream("c:/prefs.xml",FileMode.Open);
  6. 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.

  1. publicclass SQLUserPreferences : UserPreferences
  2. {
  3.     public SQLUserPreferences()
  4.     {
  5.         string connectionString ="Data Source=.SQLEXPRESS;AttachDbFilename="C:DOCUMENTS AND SETTINGSTROTTTMY DOCUMENTSVISUAL STUDIO 2005PROJECTSWINDOWSAPPLICATION5WINDOWSAPPLICATION5DATABASE1.MDF";Integrated Security=True;Connect Timeout=30;User Instance=True";
  6.         SqlConnection sqlCon =new SqlConnection(connectionString);
  8.         sqlCon.Open();
  9.         string commandString ="SELECT * FROM appSettings WHERE UserLogon = '"+
  10.         System.Environment.UserDomainName+""+
  11.         System.Environment.UserName.ToString()+"'";
  13.         SqlCommand sqlCmd =new SqlCommand(commandString, sqlCon);
  14.         SqlDataReader dr = sqlCmd.ExecuteReader();
  16.         while(dr.Read())
  17.         {
  18.             // Index 0 contains the domain/username used
  19.             // as a primary key for the database.
  20.             _DisplayName = dr.GetString(1);
  21.             _Company = dr.GetString(2);
  22.             _SomeValue = dr.GetInt32(3);
  23.         }
  25.         dr.Close();
  26.         sqlCon.Close();
  27.     }
  29.     publicvoid Save()
  30.     {
  31.         string connectionString ="Data Source=localhost; Integrated Security=SSPI; Initial Catalog=appSettings";
  32.         SqlConnection sqlCon =new SqlConnection(connectionString);
  34.         sqlCon.Open();
  35.         string commandString ="UPDATE appSettings SET "+
  36.           "DisplayName = '"+ _DisplayName +"', "+
  37.           "Company = '"+ _Company +"', "+
  38.           "SomeValue = "+ _SomeValue +
  39.           " WHERE UserLogon = '"+
  40.           System.Environment.UserDomainName+"//"+
  41.           System.Environment.UserName+"'";
  43.         SqlCommand sqlCmd =new SqlCommand(commandString, sqlCon);
  44.         sqlCmd.ExecuteNonQuery();
  45.         sqlCon.Close();
  46.     }
  47. }

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.

  1. publicclass RegUserPreferences : UserPreferences
  2. {
  3.     public RegUserPreferences()
  4.     {
  5.         RegistryKey UserPrefs = Registry.CurrentUser.OpenSubKey("SOFTWAREYour-Company-NameApp-Name", true);
  7.         if(UserPrefs !=null)
  8.         {
  9.             _DisplayName = UserPrefs.GetValue("DisplayName").ToString();
  10.             _Company = UserPrefs.GetValue("Company").ToString();
  11.             _SomeValue =int.Parse(UserPrefs.GetValue("SomeValue").ToString());
  12.         }
  13.         else
  14.         {
  15.             // Key did not exist so use defaults
  16.             _DisplayName =System.Environment.UserName;
  17.             _Company =System.Environment.UserDomainName;
  18.             _SomeValue =0;
  19.         }
  20.     }
  22.     publicvoid Save()
  23.     {
  24.         RegistryKey UserPrefs = Registry.CurrentUser.OpenSubKey("SOFTWAREYour-Company-NameApp-Name", true);
  26.         if(UserPrefs ==null)
  27.         {
  28.             // Value does not already exist so create it
  29.             RegistryKey newKey = Registry.CurrentUser.OpenSubKey("SOFTWAREYour-Company-Name", true);
  30.             UserPrefs = newKey.CreateSubKey("App-Name");
  31.         }
  33.         UserPrefs.SetValue("DisplayName", _DisplayName);
  34.         UserPrefs.SetValue("Company", _Company);
  35.         UserPrefs.SetValue("SomeValue", _SomeValue);
  36.     }
  37. }

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

Leave a Reply