2012-05-18 54 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的內部應用程序設置引發錯誤做了。