【问题标题】:What is wrong with my app.config file?我的 app.config 文件有什么问题?
【发布时间】:2012-05-26 05:33:21
【问题描述】:

我有一个如下所示的 app.config 文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TestKey" value="TestValue" />
  </appSettings>
  <newSection>
  </newSection>
</configuration>

我正在尝试以这种方式使用它:

System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(@"C:\app.config");  
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap); 

但是,它似乎不起作用。当我在读入文件后立即中断和调试时,我尝试查看configuration.AppSettings,我得到一个'configuration.AppSettings' threw an exception of type 'System.InvalidCastException'

我确定我正在阅读该文件,因为当我查看 configuration.Sections["newSection"] 时,我返回一个空的 {System.Configuration.DefaultSection}(而不是 null)。

我猜我有一些非常基本的错误...AppSettings 发生了什么?

【问题讨论】:

    标签: .net app-config


    【解决方案1】:

    您使用了错误的函数来读取 app.config。 OpenMappedMachineConfiguration 旨在打开您的 machine.config 文件,但您正在打开一个典型的 application.exe.config 文件。 以下代码将读取您的 app.config 并返回您期望的内容。

        System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = @"C:\app.config";
        System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        MessageBox.Show(configuration.AppSettings.Settings["TestKey"].Value);
    

    【讨论】:

      【解决方案2】:

      我认为是“newSection”元素导致了问题。除非你也添加一个 'configSections' 元素来声明什么是 'newSection',否则 .NET 将无法转换它。

      你需要这样的东西:

      <configSections>
        <section name="newSection" type="Fully.Qualified.TypeName.NewSection,   
        AssemblyName" />
      </configSections>
      

      首先,我会尝试删除“newSection”元素,看看这是否能改善这种情况。

      This link 解释了自定义配置部分。

      【讨论】:

      • 不幸的是,不是这样。我把 newSection 放进去只是为了确保我真的在加载文件。删除它没有任何区别。
      【解决方案3】:

      如果您阅读 MSDN 上有关您尝试使用的功能的文档:

      OpenExeConfiguration MSDN

      在你使用的方式中它会尝试查找app.config.exe的配置。如果您确实想使用 appSettings,请将它们从您的应用程序添加到配置文件的配置中,然后使用配置管理器访问它们:

      Using appsetting .net MSDN

      【讨论】:

      • 这并不奇怪...我认为 OpenExeConfiguration 不太正确,但由于我对其他选项没有运气,我想我会探索它。我删除了对我的问题的编辑,我认为这可能只是造成了更多的混乱。
      【解决方案4】:

      每当我在 webconfig 中使用密钥时,我都会这样做

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <configSections>
          <SectionGroup>
            Section Stuff
          </SectionGroup>
        </configSections>
      <appsettings>
         <add key="TestKey" value="TestValue" />
      </appSettings>
      </configuration>
      

      我不完全明白为什么,但在 configsettings 中使用应用程序设置总是会给我带来错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-21
        • 2014-09-04
        • 1970-01-01
        相关资源
        最近更新 更多