它适用于Read
,但我似乎无法做到这Write
一点。当我尝试写入文件时,它不会抛出任何 IO 异常。好像什么都没发生一样。
这是我的代码,请看GetValue()
和SetValue()
功能:
using System.Configuration;
public class AppConfig {
private string _username;
private string _password;
public AppConfig() {
_filePath = GetValue("Username");
_password = GetValue("Password");
//... more
}
public string Password {
get { return _password; }
set { SetValue("Password", value); _password = value; }
}
public string Username {
get { return _username; }
set { SetValue("Username", value); _username = value; }
}
private void SetValue(string key, string val) {
var cfg= ConfigurationManager
.OpenExeConfiguration(ConfigurationUserLevel.None);
cfg.AppSettings.Settings[key].Value = val;
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
private string GetValue(string key) {
return ConfigurationManager.AppSettings[key];
}
}
这是 app.config 文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key ="Password" value ="123456"/>
<add key ="Username" value ="hohoho"/>
</appSettings>
</configuration>
知道如何使Write
事情发生吗?谢谢你。