67

我正在使用 C#、Framework 3.5 (VS 2008)。

我正在使用将ConfigurationManager配置(不是默认的 app.config 文件)加载到配置对象中。

使用 Configuration 类,我能够得到一个ConfigurationSection,但我找不到获取该部分值的方法。

在配置ConfigurationSection中,类型为System.Configuration.NameValueSectionHandler.

对于它的价值,当我使用的方法GetSectionConfigurationManager仅在我的默认 app.config 文件上有效)时,我收到了一个对象类型,我可以将其转换为键值对的集合,我刚刚收到像字典一样的值。ConfigurationSection但是,当我从 Configuration 类接收课程时,我无法进行此类转换。

编辑:配置文件示例:

<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");

顺便说一句,2.0 不再支持 NameValueSectionHandler。

于 2013-03-04T15:00:45.150 回答
18

这是一个很好的帖子,展示了如何做到这一点。

如果要从 app.config 以外的文件中读取值,则需要将其加载到 ConfigurationManager 中。

试试这个方法:ConfigurationManager.OpenMappedExeConfiguration()

在 MSDN 文章中有一个如何使用它的示例。

于 2010-08-11T18:53:17.813 回答
14

Try using an AppSettingsSection instead of a NameValueCollection. Something like this:

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

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

于 2013-01-17T17:27:55.243 回答
7

我可以让它工作的唯一方法是手动实例化节处理程序类型,将原始 XML 传递给它,然后转换生成的对象。

看起来效率很低,但你去吧。

我写了一个扩展方法来封装它:

public static class ConfigurationSectionExtensions
{
    public static T GetAs<T>(this ConfigurationSection section)
    {
        var sectionInformation = section.SectionInformation;

        var sectionHandlerType = Type.GetType(sectionInformation.Type);
        if (sectionHandlerType == null)
        {
            throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
        }

        IConfigurationSectionHandler sectionHandler;
        try
        {
            sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
        }
        catch (InvalidCastException ex)
        {
            throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
        }

        var rawXml = sectionInformation.GetRawXml();
        if (rawXml == null)
        {
            return default(T);
        }

        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(rawXml);

        return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
    }
}

您在示例中调用它的方式是:

var map = new ExeConfigurationFileMap
{
    ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
于 2014-03-20T18:18:53.810 回答
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 回答
0

尝试这个;

信用:https ://www.limilabs.com/blog/read-system-net-mailsettings-smtp-settings-web-config

SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

string from = section.From;
string host = section.Network.Host;
int port = section.Network.Port;
bool enableSsl = section.Network.EnableSsl;
string user = section.Network.UserName;
string password = section.Network.Password;
于 2019-12-19T10:48:59.653 回答
0

这就像一个魅力

dynamic configSection = ConfigurationManager.GetSection("MyParams");
var theValue = configSection["FirstParam"];
于 2022-01-12T10:14:09.190 回答