WPF app.config 编写
我已经看到提出了这个解决方案,但似乎对我不起作用:
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = “NewValue”;
oConfig.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
它成功更改了内存中的值,但没有将其保存回配置文件。
我正在尝试在 Wpf 应用程序中执行此操作,如果这有什么区别的话。
或者是否有将用户设置保存到文件的首选方法?
I've seen this solution proposed, but doesn't seem to work for me:
Configuration oConfig = 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的应用安装在
\Program Files\
中,则它可能没有写入该文件的权限。一般来说,app.config 文件是手动修改的(至少根据我的经验)。如果您想保留用户首选项,您应该查看 .settings 文件,因为这些文件是在用户目录下的 %appdata%(或 %localappdata%)目录中创建的。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.我的猜测是使用 OpenExeConfiguration 实际上并没有打开关联的文件。例如,您可以从 XAP 运行,其中
.xap
内仍然会有.exe.config
,但它不会映射到实际文件在文件系统上。您可以通过查看
oConfig.HasFile
是否为true
来检查这一点。如果我的猜测是正确的,那么您将需要使用
OpenExeConfiguration(string)
重载; MSDN 页面上的示例有一个合理的方法来获取正确的文件名,尽管我的第一反应是尝试 System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase。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
istrue
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 trySystem.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
.