我的目标是以编程方式更新属于另一个应用程序的 .config 文件。
我从一个看起来像这样的简单配置文件开始......
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test1" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
然后我运行我的代码来更新名为的连接字符串Test1
并将其重命名为Test2
...
var configMap = new ExeConfigurationFileMap() { ExeConfigFilename = @"test\app.config" };
var externalConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
externalConfiguration.ConnectionStrings.ConnectionStrings[1].Name = "Test2";
externalConfiguration.Save(ConfigurationSaveMode.Minimal, true);
这将保存配置文件,但现在查看该文件,您会看到一些其他数据已添加到其中...
ConfigurationSaveMode.Minimal
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test2" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<trust level="Full" />
<webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
</system.web>
</configuration>
ConfigurationSaveMode.Modified
使用修改后的设置,我得到更多的“东西”......
<configuration>
<appSettings />
<configProtectedData />
<system.diagnostics />
<system.windows.forms />
<uri />
<connectionStrings>
<add name="Test2" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.net>
<authenticationModules />
<connectionManagement />
<defaultProxy />
...snip...
这些数据是什么,它来自哪里?更重要的是如何阻止它被写入我的文件?