msl*_*viu 1 c# wpf app-config application-settings
我正在尝试使用下面的代码更新 app.config 文件中的值(该值在“属性”>“设置”中定义为“应用程序范围”)
System.Configuration.Configuration configApp = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MessageBox.Show(configApp.AppSettings.Settings.Count.ToString()); //this shows 0
configApp.AppSettings.Settings["PontajAdminPwd"].Value = "dsfs";
configApp.Save(ConfigurationSaveMode.Full);
Run Code Online (Sandbox Code Playgroud)
但它说 configApp.AppSettings.Settings 是空的......
这是我的 app.config 文件的一部分
System.Configuration.Configuration configApp = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MessageBox.Show(configApp.AppSettings.Settings.Count.ToString()); //this shows 0
configApp.AppSettings.Settings["PontajAdminPwd"].Value = "dsfs";
configApp.Save(ConfigurationSaveMode.Full);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
谢谢
编辑1:我很着急,所以我采用了这里提出的解决方案(手动更改app.config文件后直接文件访问 - 使用appSettings而不是applicationSettings):http:
//www.longhorncorner.com/uploadfile/rahul4_saxena /update-app-config-key-value-at-run-time-in-wpf/
configApp.AppSettings.Settings.Count.ToString()这将尝试从<appSettings>部分读取设置,而不是<applicationSettings>. 文件名也应该是app.config.
在您的情况下,您将需要使用Properties.Settings静态类来从applicationSettings. 你可以试试PontajWPF.Properties.Settings.Default.PontajAdminPwd
应用程序范围设置是只读的,并且只能在设计时或通过在应用程序会话之间更改 .exe.config 文件来更改。
但是,用户范围设置可以在运行时写入,就像更改任何属性值一样。新值在应用程序会话期间持续存在。您可以通过调用 Settings.Save 方法在应用程序会话之间保留对用户设置的更改。这些设置保存在 User.config 文件中。
在MSDN上阅读更多内容
希望这可以帮助。