2012-05-18 51 views
13

我有一个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}(而不是空)。

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

回答

12

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

我认为'newSection'元素导致了这个问题。除非你也添加了一个'configSections'元素,为了声明'newSection'是什么,.NET将无法投射它。

你需要的东西,如:

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

在第一种情况下,我会尝试删除“newSection”元素,看是否能改善这种情况。

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

+0

不幸的是,事实并非如此。我把newSection放在刚才确定我真的在加载文件。删除它没有区别。 – Beska

3

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

OpenExeConfiguration MSDN

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

Using appsetting .net MSDN

+0

这并不令人感到意外...我并不认为OpenExeConfiguration很正确,但由于我没有碰到其他选项,我以为我会探索它。我已经删除了对我的问题的编辑,我认为这可能会导致更多的混淆。 – Beska

2

任何时候,我已经使用了关键我的webconfig我已经像这样

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

我不完全理解为什么,但它总是在我有configsettings的内部应用程序设置引发错误做了。