将更改保存到自定义配置文件时出错

Error while saving changes to custom config file

我正在使用自定义配置文件。我可以从中获取数据但无法修改它。

app.config 文件:

<configuration>
    <configSections>
        <section name="newAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </configSections>
    <newAppSettings file="D:\Projects\MLSImporter\MLS Application\customApp.config"/>
    <runtime>

customApp.config:

<?xml version="1.0" encoding="utf-8" ?>
<newAppSettings>
<add key="Data Source" value="xxxxxxxxxx"/>
<add key="Database" value="xxxxxxxxx"/>
<add key="User ID" value="xxxxxxxxxxxx"/>
<add key="Password" value="xxxxxxxxxxxxxxxxxxxxx"/>
</newAppSettings>

访问密钥的代码是:

var a = ((System.Collections.Specialized.NameValueCollection)(System.Collections.Specialized.NameValueCollection)System.Configuration.ConfigurationManager.GetSection("newAppSettings"));
a["Data Source"] = txtServer.Text;

你能帮我看看如何保存对此自定义文件的更改吗?

要求

using System.Configuration;  

阅读

var appSettings = ConfigurationManager.AppSettings;  
string result = appSettings[key] ?? "Not Found";  

写入

var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
    settings.Add(key, value);
}
else
{
    settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);