问题
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