【发布时间】:2011-07-15 17:55:48
【问题描述】:
我不喜欢 .NET Framework 中的标准配置机制。 (ConfgurationManager、ConfigurationSection 等)。
我想要更简单的功能来管理我的应用程序配置文件。
例如,我想在我的应用程序文件夹中创建一个名为“设置”的文件夹。有几个名为的配置文件。
请看一下:
Settings:
- smtp.config
- database.config
- something.config
假设“smtp.config”文件具有以下简单结构:
<smtp>
<username>something</username>
<hostname>something</hostname>
...
</smtp>
我想创建以下类:
public class MySmtpSettings : SomeBaseClassFromSomeConfigLibrary
{
// May be some simple attributes here
public string username;
// May be some simple attributes here. For example:
// Like XPath: [ConfigAttr("smtp\username")], or simply: ConfigAttr("username")
public string hostname;
...
// Only code containing properties declaration.
}
我想使用我的设置对象:
var settings = new MySmtpSettings("smtp.config");
var hostname = settings.Hostname;
我不想使用 ConfigurationSection 类。看起来很难。
你知道我在哪里可以找到一个可扩展的、简单的开源库吗?
UPD。
@jjrdk:感谢您的回答,但我通常使用 ConfigurationSection 类创建下一个代码:
public class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("username")]
public ConfigurationTextElement<string> Username
{
get { return (ConfigurationTextElement<string>)this["username"]; }
set { this["username"] = value; }
}
// ...
{
public class ConfigurationTextElement<T> : ConfigurationElement
{
private T _value;
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
_value = (T)reader.ReadElementContentAs(typeof(T), null);
}
public T Value
{
get { return _value; }
}
}
看起来并不简单。也许我做了一些我不明白的事情?
【问题讨论】:
-
我建议您重新考虑您对 ConfigurationSection 类的看法。这并不难,并且完全按照您的要求进行。将其视为一种学习体验。
-
你不喜欢 .NET Framework 中的标准配置机制吗?
-
@RQDQ:描述类和文件之间的链接需要大量代码。
标签: c# xml configuration configuration-files