我的app.config文件有什么问题?

时间:2012-05-18 16:07:24

标签: .net app-config

我有一个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会发生什么?

4 个答案:

答案 0 :(得分:17)

您使用了错误的函数来读取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);

答案 1 :(得分:3)

我认为'newSection'元素导致了这个问题。除非您添加'configSections'元素,要声明'newSection'是什么,.NET将无法强制转换它。

您需要以下内容:

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

在第一个例子中,我尝试删除'newSection'元素以查看是否可以改善这种情况。

This link解释了自定义配置章节。

答案 2 :(得分:3)

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

OpenExeConfiguration MSDN

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

Using appsetting .net MSDN

答案 3 :(得分:2)

任何时候我在我的网络配置中使用了密钥,我就这样做了

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

我不完全理解为什么但是在配置设置中有应用程序设置时我总是会犯错误。

相关问题