Reputation: 73
I want to add some variables to my C# app settings, is there any way to do this with code. I can do that by going to project, then myApp properties and so on but i want to add setting while app is running so i should do it by code. Or how can I make setting type a LinkedList<> of something like that, so than it would be available to add some items to it.
Upvotes: 4
Views: 158
Reputation: 14233
Here is some code I use to manipulate an existing AppSetting:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["PrinterID"].Value = "Some Value";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
To add a new AppSetting, you can change the second line to:
config.AppSettings.Settings.Add("PrinterID", "Some Value");
Upvotes: 4
Reputation: 13513
Just a hint: This way you can not add variables (directly) but you can save a variable:
1 - Declare a variable at settings and set it's scope to User instead of Application; the change it's value and then call Properties.Settings.Default.Save(); BUT this will not save at the assembly that is executing, instead it will go into the proper AppData folder of that application.
2 - For adding new values you can define a serializable key-value collection (as @keyboardP suggested a NameValueCollection i.e.) setting and change it's values at run-time.
3 - (A total different approach:) You can use another, separate chain of functionality for that purpose (like an xml,txt,ini file or your local or embedded database) because anyway you have to take care of concurrent reads of the setting which Properties.Settings.Default does not provide out of the box (although this is the case if you have any paralleled parts in your app).
Upvotes: 0
Reputation: 69372
You can use the ConfigurationManager.AppSettings property. Instead of a LinkedList
, it uses a NameValueCollection structure.
Upvotes: 1