WPF app.config writing
I've seen this solution proposed, but doesn't seem to work for me:
Configuration oConfig =开发者_StackOverflow社区 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = “NewValue”;
oConfig.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
It successfully changes the value in memory, but does not save it back to the config file.
I'm trying to do this in a Wpf app, if that makes any difference.
Or is there a preferred way to save user settings to a file?
If your app is installed in \Program Files\
then it may not have permissions to write to the file. Generally, app.config files are modified by hand (in my experience, at least). If you want to persist user preferences, you should look into a .settings file as these are created in the %appdata% (or %localappdata%) directory, which is under the user's directory.
My guess is that using OpenExeConfiguration
does not actually open the associated file. For example, you could be running from a XAP, where there would still be a .exe.config
inside the .xap
, but it doesn't map to an actual file on the filesystem.
You could probably check this by seeing if oConfig.HasFile
is true
or not.
If my guess is correct, then you'll need to use the OpenExeConfiguration(string)
overload; the sample on the MSDN page has a reasonable way to get the right filename, although my first instinct was instead to try System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
.
精彩评论