C#: App Settings example

The following example shows a basic class for saving settings and preferences. It can be extended easily for your application. It saves the settings in a XML file in the users "AppData" directory.

Code

public class AppSettings
{
    /// <summary>
    /// Name of the application
    /// </summary>
    private const String APP_NAME = "MyApplicationName";

    /// <summary>
    /// Filename for the settings
    /// </summary>
    private const String SETTINGS_FILENAME = "settings.xml";

    /// <summary>
    /// Name of the xml root
    /// </summary>
    private const String XML_ROOT = "xml";


    private static String _lang;

    public static String Lang
    {
        get { return AppSettings._lang; }
        set { AppSettings._lang = value; }
    }


    /// <summary>
    /// Saves the settings
    /// </summary>
    public static void Save()
    {
        String appData = GetSettingsPath();
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement(XML_ROOT);

        //save variables here
        CreateTextElement(root, doc.CreateElement("Lang"), Lang);

        doc.AppendChild(root);
        doc.Save(appData);
    }

    /// <summary>
    /// Loads the settings
    /// </summary>
    public static void Load()
    {
        String appData = GetSettingsPath();

        if (!File.Exists(appData))
        {
            Init();
        }

        XmlDocument doc = new XmlDocument();
        doc.Load(appData);

        //load variables here
        Lang = GetSetting(doc, "Lang", Consts.LANG_DE);  

    }

    /// <summary>
    /// Inits the settings with defaults
    /// </summary>
    public static void Init()
    {
        //Init your variables here
        Lang = Consts.LANG_DE;s

        Save();
    }

    #region InternalCode

    /// <summary>
    /// Creates a text element in the xml file
    /// </summary>
    /// <param name="root"></param>
    /// <param name="node"></param>
    /// <param name="text"></param>
    private static void CreateTextElement(XmlNode root, XmlNode node, string text)
    {
        node.InnerText = text;
        root.AppendChild(node);
    }

    /// <summary>
    /// Gets the settings path, if it not exists it is created
    /// </summary>
    /// <returns></returns>
    private static String GetSettingsPath()
    {
        String appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

        appData = Path.Combine(appData, APP_NAME);

        if (!Directory.Exists(appData))
        {
            Directory.CreateDirectory(appData);
        }

        appData = Path.Combine(appData, SETTINGS_FILENAME);
        return appData;
    }

    /// <summary>
    /// Loads a node, if the node cannot be found the default value is used
    /// </summary>
    /// <param name="settingName"></param>
    /// <param name="defaultValue"></param>
    private static String GetSetting(XmlDocument doc, String settingName, String defaultValue) 
    {
        String value = "";

        try {
            value = doc.SelectSingleNode("/" + XML_ROOT + "/" + settingName).InnerText;   
        } catch {
            value = defaultValue;
        }

        return value;
    }

    #endregion
}

You can add your own settings to the class like that:

private static String _lang;

public static String Lang
{
    get { return AppSettings._lang; }
    set { AppSettings._lang = value; }
}

You also need to add the logic for saving and loading each property. See Load and Save methods.

Load on Start Up

For example you can load the settings in the Main method of your application. After that its available in your application:

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
    //Load settings
    AppSettings.Load();

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}

You can access a setting value from the AppSettings class:

MessageBox.Show("Language: " + AppSettings.Lang

Set and Save Settings to File

Setting and saving is also easy:

AppSettings.Lang = "de";
AppSettings.Save();

Werbung



comments powered by Disqus

Copyright Dunkel & Iwer GbR | Datenschutzerklärung | Impressum