我正在.NETFramework4.5上创建一个应用程序
每当我想加载app config值(appsettings部分)并写入更改时,如果刷新该部分,就看不到我的更改。我做错什么了?我该怎么解决呢?
代码
private void LoadConfig()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
for (int i = 0; i < appSettings.Count; i++)
{
switch (appSettings.GetKey(i))
{
case "initialCatalog":
txtInitialCatalog.Text = appSettings.GetValues(i)[0];
break;
case "dataSource":
txtDatasource.Text = appSettings.GetValues(i)[0];
break;
case "userName":
txtUsername.Text = appSettings.GetValues(i)[0];
break;
case "password":
txtPassword.Text = appSettings.GetValues(i)[0];
break;
case "portalUrl":
txtUrl.Text = appSettings.GetValues(i)[0];
break;
}
}
}
private void SaveConfig()
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
appSettings["initialCatalog"].Value = txtInitialCatalog.Text;
appSettings["dataSource"].Value = txtDatasource.Text;
appSettings["userName"].Value = txtUsername.Text;
appSettings["password"].Value = txtPassword.Text;
appSettings["portalUrl"].Value = txtUrl.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
app.config文件
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="initialCatalog" value="a" />
<add key="dataSource" value="b" />
<add key="password" value="c" />
<add key="userName" value="d" />
<add key="portalUrl" value="e" />
<add key="poolingTime" value="60000" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
当表单被激活时,我调用readconfig()并在按下按钮(确定或应用)时保存数据我关闭应用程序我重新运行它,但没有对app.config文件进行任何更改
有什么想法吗???
最佳答案
我认为发生的情况是,您正在visual studio中进行测试,它会将app.config复制到调试/发布目录,并将其重命名为application.vshost.exe.config,每次启动应用程序时,它都会重置。请尝试在visual studio外部运行可执行文件,该文件将使用yourcapplication.exe.config文件,并查看该文件是否适合您。如果我在visual studio之外运行应用程序,则您的代码对我有效,并在应用程序重新启动时保留您的更改。