C#: Storing settings in a SQLite database for a Windows Forms application


I find it’s a pretty common requirement to store settings for an application, such as: “recently opened files”, “last opened path” or other user preferences. I’ve seen this done using INI configuration files, XML and JSON text files. A few years ago I heard about SQLite; how the likes of Google Chrome were using it for storing configurations.

So, I built my own helper to handle reading and writing of settings. This class uses a very old design pattern that was ported over from my early days with PHP (before ORM). The original pattern was taken from an old Microsoft project management product which dated back to 1999. This uses SQL with string-tokens and a variable number of parameters (known as, params or varargs) to build a query string.

I still quite like how simple it is and how well it works after all these years.

I’ve changed the SQLite dependency a few times, in the current version I’m using System.Data.SQLite by SQLite Development Team.

Anyway, let’s get started.

 

1. Setup

I typically match the database filename to the application’s executable name: such that FormApplication1.exe will have a FormApplication1.db in the same folder.


using RyzStudio.Data.SQLite;

protected SQLiteDatabase appSettingsDB = new SQLiteDatabase();

bool rs = appSettingsDB.Create(Path.ChangeExtension(Application.ExecutablePath, "db"), false, null, true);
if (!rs)
{
  MessageBox.Show(appSettingsDB.LastError);
  return;
}

 

2. Write Values


appSettingsDB.SetConfig("setting1", 1);
appSettingsDB.SetConfig("setting2", "two");
appSettingsDB.SetConfig("setting3", true);

 

3. Read Values


int setting1 = appSettingsDB.GetIntConfig("setting1", 0);
string setting2 = appSettingsDB.GetConfig("setting2", "");
bool setting3 = appSettingsDB.GetBoolConfig("setting3", false);

 

4. Finish


appSettingsDB.Close();

 

Well, that’s it.

I hope someone finds this interesting or useful.

SQLiteDatabase.cs

Social Media

 Share Tweet

Categories

Programming

Tags

.NET C#

Post Information

Posted on Thu 4th Apr 2019

Modified on Sat 5th Aug 2023