我正在使用C#,Framework 3.5(VS 2008)。
我正在使用ConfigurationManager
将配置(不是默认的app.config文件)加载到Configuration对象中。
使用Configuration类,我能够获得ConfigurationSection
,但我找不到获取该部分值的方法。
在配置中,ConfigurationSection
的类型为System.Configuration.NameValueSectionHandler
。
当我使用GetSection
的方法ConfigurationManager
时(仅当它在我的默认app.config文件中时),我得到了一个对象类型,我可以投进入键值对的集合,我刚接收到像Dictionary一样的值。但是,当我从Configuration类收到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"]);
答案 0 :(得分:20)
遭遇确切问题。问题是因为.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");
btw 2.0中不再支持NameValueSectionHandler。
答案 1 :(得分:17)
Here's这是一篇很好的文章,展示了如何做到这一点。
如果要从app.config以外的文件中读取值,则需要将其加载到ConfigurationManager中。
尝试此方法:ConfigurationManager.OpenMappedExeConfiguration()
有一个如何在MSDN文章中使用它的例子。
答案 2 :(得分:13)
尝试使用AppSettingsSection
代替NameValueCollection
。像这样:
var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
答案 3 :(得分:8)
我能让它工作的唯一方法是手动实例化部分处理程序类型,将原始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>();
答案 4 :(得分:3)
这是一个老问题,但我使用以下课程来完成这项工作。它基于Scott Dorman's blog:
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));
答案 5 :(得分:2)
以下是前面提到的this blog的一些示例:
<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();
答案 6 :(得分: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;