how to get Properties.Settings.Default with a string?

user3894648 picture user3894648 · Jul 31, 2014 · Viewed 9.3k times · Source

I have a Winforms/C# application and I am migrating from xml configuration file to application settings. I would like to know if it is possible to access dynamically application settings (Properties.Settings.Default).

I have 4 configurations possible for my application with the settings associated, which I logically named name1, name2, name3, name4, server1, server2 etc.. Instead of assigning them a value like

Properties.Settings.Default.name1 = textbox.txt;

I would like to to something like this regarding the configuration they belong to :

class ApplicationSettings
{

    int no;

    ApplicationSettings(int no)
    {
        this.no = no;
    }

    private void save()
    {
        Properties.Settings.Default.Properties["name"+no] = "value";
    }

}

The technic seems to work only for SettingsProperties, as seen here. Do you know if there is a way to do this ?

Answer

wbennett picture wbennett · Jul 31, 2014

You need to use the [] operator and convert the integer to a string, like so:

internal static class ApplicationSettings
{

    //added public static because I didn't see how you planned on invoking save
    public static void Save(int no, string value)
    {
        //sets the nameX
        Properties.Settings.Default["name"+no.ToString()] = value;
        //save the settings
        Properties.Settings.Default.Save();
    }

}

Usage

ApplicationSettings.Save(1,"somesetting");