I need to give the user the ability to change application settings, in this case the location for the application database. I noticed that Application Settings are read only at run time, but this needs to be application-wide, not user-specific. How do I persist an application-wide connection string in windows.forms that is changeable at runtime?

- 59,778
- 26
- 187
- 249

- 31
- 2
-
See also http://stackoverflow.com/questions/453161/best-practice-to-save-application-settings-in-a-windows-application – Ruben Bartelink Mar 11 '11 at 08:54
2 Answers
You can use
ConfigurationManager.AppSettings.Set()
Also
ConnectionStringSettings.ConnectionString Property
Can be set too.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add("test","tada");
config.Save(ConfigurationSaveMode.Minimal, true);

- 162,879
- 31
- 289
- 284
-
-1: Only for user-level stuff, and you dont want to write to Progrm Files directory – Ruben Bartelink Nov 25 '09 at 10:43
-
-1 removed in light of edit - but if you are going this route, you should definitely not be writing beside the EXE or in the EXE's .config file - you should be writing to the AppSettings directory – Ruben Bartelink Nov 25 '09 at 11:08
There isnt a direct way in the framework using the newer Settings classes - you can save user-level settings with the Settings support, but not application/machine level. Easiest way is to XmlSerialize a class and store it in a directory that is shared between all users with write acccess when they are running un-elevated such as the Public Documents folder (the program directory shouldnt be written to), e.g.. Environment.SpecialFolder.CommonApplicationData
EDIT: Yes, the old appSettings mechanism has a way of writing, but that's bad news - the newer Settings stuff omits this facility as it is bad news for lots of reasons to try to write to config files in Program Files

- 59,778
- 26
- 187
- 249
-
That would be user-wide, not application-wide, no? – BlueRaja - Danny Pflughoeft Mar 09 '11 at 19:56
-
@Blue Raja - Danny Pflughoeft: That's what the text of my answer said. I added the italicised section just now to make it 100% clear, HTH... – Ruben Bartelink Mar 10 '11 at 10:13
-
I meant that the `%AppData%` directory is user-wide, not application-wide - is that the same thing as the *"AppSettings directory"*? – BlueRaja - Danny Pflughoeft Mar 10 '11 at 16:56
-
@BlueRaja - Danny Pflughoeft: Yes, having actually read my answer, I see it avoids the question nicely in that it doesnt say *where* to /actually/ put it - a common documents folder is the answer, and is much better than e.g. adjusting the permissions on a Program Files sub directory or allowing onself to be redirected via virtualization to ProgramData – Ruben Bartelink Mar 10 '11 at 20:24