在configSource中使用外部.config文件会产生错误

cha*_*nya 9 .net c# app-config

我正在玩如何使用Configuration Manager在App.config文件中读取/写入C#中的WPF应用程序的自定义部分.我阅读了关于.NET 2.0 Configuration Demystified的这篇优秀文章,它在使用配置文件方面给了我很多帮助.这是我写的初始App.config文件,它工作正常.

App.config中

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="example" type="CustomConfig.ExampleSection, CustomConfig" />
  </configSections>
  <example version="A sample string value." />
  <appSettings>
    <add key="version_string" value="1.01" />
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

但当我更改App.config文件时,我的自定义部分将从configSource中提到的外部配置文件中读取,Visual Studio给出了一个错误

configSource文件的格式必须是包含该部分名称的元素.

以下是App.config和example.config文件

更改了App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="example" type="CustomConfig.ExampleSection, CustomConfig" />
  </configSections>
  <example configSource="example.config" />
  <appSettings>
    <add key="version_string" value="1.01" />
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

example.config

<?xml version="1.0"?>
<example>
    <add key="version" value="blahblah" />
</example>
Run Code Online (Sandbox Code Playgroud)

equ*_*man 8

我得到了同样的错误.在我的情况下,由于我有两个文件中的密钥,然后检测appSettings标签为重复.

如果您需要在web.config中保存一些与项目相关的密钥,并在另一个文件中保存您的个性化密钥(建议出于安全原因),请使用fileproperty而不是configSource.

web.config文件:

<configuration>
  <appSettings file="../AppSettings.config">
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

AppSettings.config文件:

<?xml version="1.0"?>

<appSettings>
  <add key="RutaBodega" value="D:\Test\Card"/>
  <add key="CodeLen" value="5"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)

希望能帮到别人!


mar*_*c_s 4

Visual Studio 的编辑器/智能感知有一个缺点,它会抱怨该configSource=属性 - 但它绝对合法,而且确实有效;我每天都在各种生产系统中使用它。

我的建议:尝试一下!:-) 运行代码 - 我很确定它会起作用(你的配置对我来说看起来不错)。

更新:好的 - 看来你完全改变了标签的样式<example>。在你的原件中app.config你有:

<example version="A sample string value." />
Run Code Online (Sandbox Code Playgroud)

因此,当然,您的外部化example.config必须包含相同的值和相同的结构:

<?xml version="1.0"?>
<example version="A sample string value." />
Run Code Online (Sandbox Code Playgroud)

你能尝试用这个example.config吗?