.net desktop app - how do store/change application settings or connection strings?
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?
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);
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
精彩评论