[C#] Basic setting file that easy to extend using JSON

  1. Home
  2. /
  3. Technologies
  4. /
  5. [C#] Basic setting file that easy to extend using JSON

[C#] Basic setting file that easy to extend using JSON

Posted in : Technologies on by : zquanghoangz Comments:

When we create an application then want to keep all the user settings from the last run, the method that I usually use is create a setting file that store keys, values data.

In this post, I show an example how to do it and it’s kind of reusable code for your next application.

Here are code then explanations:

using System.IO; using Newtonsoft.Json; namespace MyApp.Settings { public interface ISettings { string ApplicationName { get; set; } string UserName { get; set; } string Password { get; set; } string DataFile { get; set; } string BackupFile { get; set; } } public class Settings : ISettings { public string ApplicationName { get; set; } public string UserName { get; set; } public string Password { get; set; } public string DataFile { get; set; } public string BackupFile { get; set; } } public static class SettingFactory { private const string DefaultSettingFile = "setting.json"; private static string _settingFile; public static string SettingFile { get { return string.IsNullOrEmpty(_settingFile) ? DefaultSettingFile : _settingFile; } set { _settingFile = value; } } public static ISettings Load() { var json = File.ReadAllText(SettingFile); return JsonConvert.DeserializeObject<ISettings>(json); } public static void Save(ISettings settings) { var json = JsonConvert.SerializeObject(settings); File.WriteAllText(SettingFile, json); } } }
SettingCode

The ISettings interface and Settings class is the model that present all setting keys values that you want to store in setting file. This part is what I describe by extendable. You can add, update and delete properties in the interface to those configures that your application needed.

The SettingFactory class, mostly don’t need to change, that provide Load and Save setting for your application. In here, you can change the setting file name or use the default one, that quite flexible for using in an application.

Thank for your reading.

Leave a Reply

Your email address will not be published. Required fields are marked *