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

﹥>﹥吖頭↗ 提交于 2020-01-03 10:39:10

问题


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 ?


回答1:


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");


来源:https://stackoverflow.com/questions/25060519/how-to-get-properties-settings-default-with-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!