2010-12-07 7 views
3

私はこれを実行すると、カスタム構成例外(下のコード)を読むように設計された単純なコンソールアプリケーションを持っています。ConfigurationManager.GetSectionを呼び出すときに「無効なキー値」というメッセージが表示されてConfigurationErrorsExceptionが発生します。誰かが私が間違って行ったことを見ることができますか?ConfigurationErrorsException "無効なキー値"、何が間違っていますか?

設定ファイル

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    <section name="MySection" type="ConsoleApplication1.MySection, ConsoleApplication1" /> 
    </configSections> 
    <MySection> 
    <add name="MyName" value="MyValue" /> 
    </MySection> 
</configuration> 

コード

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Serialization; 
using System.Configuration; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      MySection section = (MySection)ConfigurationManager.GetSection("MySection"); 

      Console.WriteLine("Done"); 
     } 
    } 

    public class MySection : ConfigurationSection 
    { 
     [ConfigurationProperty("", IsDefaultCollection = true)] 
     public MyCollection Collection 
     { 
      get 
      { 
       return (MyCollection)this[""]; 
      } 
     } 
    } 

    public class MyCollection : ConfigurationElementCollection 
    { 
     protected override ConfigurationElement CreateNewElement() 
     { 
      return new MyElement(); 
     } 

     protected override object GetElementKey(ConfigurationElement element) 
     { 
      return ((MyElement)element).Name; 
     } 
    } 

    public class MyElement : ConfigurationElement 
    { 
     [ConfigurationProperty("name")] 
     public string Name { get; set; } 

     [ConfigurationProperty("value")] 
     public string Value { get; set; } 


    } 
} 

例外

System.Configuration.ConfigurationErrorsException was unhandled 
    Message=Invalid key value. (C:\Users\martin.brown\documents\visual studio 2010\Projects\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe.config line 7) 
    Source=System.Configuration 
    BareMessage=Invalid key value. 
    Filename=C:\Users\martin.brown\documents\visual studio 2010\Projects\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe.config 
    Line=7 
    StackTrace: 
     at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) 
     at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) 
     at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) 
     at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) 
     at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) 
     at System.Configuration.BaseConfigurationRecord.GetSection(String configKey) 
     at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName) 
     at System.Configuration.ConfigurationManager.GetSection(String sectionName) 
     at ConsoleApplication1.Program.Main(String[] args) in C:\Users\martin.brown\documents\visual studio 2010\Projects\ConsoleApplication1\Program.cs:line 14 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 

答えて

4

キーMYNAMEを追加する必要があります。

... 
<MySection> 
    <add name="MyName" value="MyValue" /> 
</MySection> 
... 

へ:

... 
<MySection> 
    <MyElements> 
     <add name="MyName" value="MyValue" /> 
    </MyElements> 
</MySection> 
... 

、その後、少しコードを変更:

public class MySection : ConfigurationSection 
{ 
    [ConfigurationProperty("MyElements", IsDefaultCollection = true)] 
    public MyCollection Collection{get {return (MyCollection) this["MyElements"];}} 
} 

public class MyElement : ConfigurationElement 
{ 
    [ConfigurationProperty("name")] 
    public string Name 
    { 
     get {return (string) (base["name"]);} 
     set {base["name"] = value;} 
    } 

    [ConfigurationProperty("value")] 
    public string Value 
    { 
     get {return (string) (base["value"]);} 
     set {base["value"] = value;} 
    } 
} 

からあなたの設定を変更し

変更ただし、それはいくつかのマイナーなをすることによって動作するように取得することができます

MyCollectionクラスは変更されません)

そして、これは動作しますし、また、あなたの設定で複数の値を追加することができます:

... 
<MySection> 
    <MyElements> 
     <add name="MyName1" value="MyValu1e" /> 
     <add name="MyName2" value="MyValue2" /> 
    </MyElements> 
</MySection> 
... 
+2

エラーは、基本のConfigurationElementのコレクションからMyElement.Nameプロパティが取得されなかったために発生していることが判明しました。 ConfigSectionにデフォルトのコレクションno nameを指定すると、要素を省略することができます。ご協力ありがとうございました。 –

+0

同じ問題が、プロパティのbase ["name"]を呼び出さなかった。 –

0
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Serialization; 
using System.Configuration; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
       var section = (MySection)ConfigurationManager.GetSection("MySection"); 

      Console.WriteLine("Done"); 
     } 
    } 

    public class MySection : ConfigurationSection 
    { 
     [ConfigurationProperty("name", IsKey = true, DefaultValue = "", IsRequired = true)] 
     public string Name 
     { 
      get { return (string)this["name"]; } 
      set { this["name"] = value; } 
     } 

     [ConfigurationProperty("value")] 
     public string Value 
     { 
      get { return (string)this["value"]; } 
      set { this["value"] = value; } 
     } 

    } 

    public class MyCollection : ConfigurationElementCollection 
    { 
     protected override ConfigurationElement CreateNewElement() 
     { 
      return new MyElement(); 
     } 

     protected override object GetElementKey(ConfigurationElement element) 
     { 
      return ((MyElement)element).Name; 
     } 
    } 

    public class MyElement : ConfigurationElement 
    { 
     [ConfigurationProperty("name", IsKey = true, DefaultValue = "", IsRequired = true)] 
     public string Name 
     { 
      get { return (string)this["name"]; } 
      set { this["name"] = value; } 
     } 

     [ConfigurationProperty("value")] 
     public string Value 
     { 
      get { return (string)this["value"]; } 
      set { this["value"] = value; } 
     } 


    } 
} 
0

あなたは値私はカスタムセクションは、あなたがやろうとしている方法が定義されて見ていませんでした

<add name="MyName" value="your value" /> 
+0

私はこれを試みても、同じエラーが発生しています。 –

1

それが誰を助けている場合、私はこれと同じエラーが発生しましたが、別の理由で。それはカスタムConfigurationElementオブジェクトからNULL可能列挙値を取得して、より具体的には

protected override Object GetElementKey(ConfigurationElement element) 
{ 
    return ((EmulatorPositionElement)element).Method; 
} 

:私のカスタムConfigurationElementCollectionのクラスでは、GetElementKey()メソッドは時々ヌルた値を返していました

[ConfigurationProperty("method", IsRequired = true)] 
public string MethodString 
{ 
    get { return (string)this["method"]; } 
    set { this["method"] = value; } 
} 

public Method? Method 
{ 
    get { return (MethodString.Trim() == "*") ? null : (Method?)Enum.Parse(typeof(Method), MethodString.Trim(), true); } 
    set { MethodString = (value == null) ? "*" : value.ToString(); } 
} 

このConfigurationProperty値がnullだった設定ファイルに子要素があるときはいつでもこのエラーが発生します。

<position method="*" ... 
関連する問題