67

C#、Framework 3.5 (VS 2008) を使用しています。

を使用してConfigurationManager、構成 (デフォルトの app.config ファイルではない) を構成オブジェクトに読み込みます。

Configuration クラスを使用して を取得できましたがConfigurationSection、そのセクションの値を取得する方法が見つかりませんでした。

構成でConfigurationSectionは、 のタイプはSystem.Configuration.NameValueSectionHandlerです。

価値があるのは、のメソッドを使用したGetSectionときConfigurationManager(デフォルトのapp.configファイルにある場合にのみ機能する)、キーと値のペアのコレクションにキャストできるオブジェクトタイプを受け取りました。 Dictionary のような値。ConfigurationSectionただし、構成クラスからクラスを受け取ったときは、そのようなキャストを行うことができませんでした。

編集: 構成ファイルの例:

<configuration>
  <configSections>
    <section name="MyParams" 
             type="System.Configuration.NameValueSectionHandler" />
  </configSections>

  <MyParams>
    <add key="FirstParam" value="One"/>
    <add key="SecondParam" value="Two"/>
  </MyParams>
</configuration>

app.config にあるときに使用できた方法の例 (「GetSection」メソッドは、デフォルトの app.config 専用です):

NameValueCollection myParamsCollection =
             (NameValueCollection)ConfigurationManager.GetSection("MyParams");

Console.WriteLine(myParamsCollection["FirstParam"]);
Console.WriteLine(myParamsCollection["SecondParam"]);
4

8 に答える 8

27

正確な問題に苦しんでいます。問題は、.configファイルのNameValueSectionHandlerが原因でした。代わりにAppSettingsSectionを使用する必要があります。

<configuration>

 <configSections>
    <section  name="DEV" type="System.Configuration.AppSettingsSection" />
    <section  name="TEST" type="System.Configuration.AppSettingsSection" />
 </configSections>

 <TEST>
    <add key="key" value="value1" />
 </TEST>

 <DEV>
    <add key="key" value="value2" />
 </DEV>

</configuration>

次にC#コードで:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");

ところで、NameValueSectionHandlerは2.0ではサポートされなくなりました。

于 2013-03-04T15:00:45.150 に答える
18

これは、その方法を示す良い投稿です。

app.config 以外のファイルから値を読み取りたい場合は、それを ConfigurationManager にロードする必要があります。

この方法を試してください: ConfigurationManager.OpenMappedExeConfiguration()

MSDN の記事に使用方法の例があります。

于 2010-08-11T18:53:17.813 に答える
14

AppSettingsSectionの代わりに を使用してみてくださいNameValueCollection。このようなもの:

var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;

ソース: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d5079420-40cb-4255-9b3b-f9a41a1f7ad2/

于 2013-01-17T17:27:55.243 に答える
4

これは古い質問ですが、次のクラスを使用して仕事をしています。Scott Dorman のブログに基づいています。

public class NameValueCollectionConfigurationSection : ConfigurationSection
{
    private const string COLLECTION_PROP_NAME = "";

    public IEnumerable<KeyValuePair<string, string>> GetNameValueItems()
    {
        foreach ( string key in this.ConfigurationCollection.AllKeys )
        {
            NameValueConfigurationElement confElement = this.ConfigurationCollection[key];
            yield return new KeyValuePair<string, string>
                (confElement.Name, confElement.Value);
        }
    }

    [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)]
    protected NameValueConfigurationCollection ConfCollection
    {
        get
        {
            return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME];
        }
    }

使い方は簡単です:

Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
NameValueCollectionConfigurationSection config = 
    (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams");

NameValueCollection myParamsCollection = new NameValueCollection();
config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp));
于 2013-10-03T13:58:07.573 に答える
3

前述のこのブログの例を次に示します。

<configuration>    
   <Database>    
      <add key="ConnectionString" value="data source=.;initial catalog=NorthWind;integrated security=SSPI"/>    
   </Database>    
</configuration>  

値を取得:

 NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database");         
    labelConnection2.Text = db["ConnectionString"];

-

もう一つの例:

<Locations 
   ImportDirectory="C:\Import\Inbox"
   ProcessedDirectory ="C:\Import\Processed"
   RejectedDirectory ="C:\Import\Rejected"
/>

値を取得:

Hashtable loc = (Hashtable)ConfigurationSettings.GetConfig("Locations"); 

labelImport2.Text = loc["ImportDirectory"].ToString();
labelProcessed2.Text = loc["ProcessedDirectory"].ToString();
于 2016-09-28T16:29:15.447 に答える