我有我的 app.config
文件 ArrayOfString
入口。每个条目都包含一个分号分隔的字符串。如果可能的话,我希望能够使用 lambda 来解析 List<>
中的值。基于输入标准。但我想要它根据该标准找到的第一个条目。或者有没有更好的方法使用 app.config
文件?
例如..
如果我想找到包含 [source],[filetype]
的第一个条目并返回文件路径。
示例 app.config
条目。
SOURCE;FLAC;112;2;\\sourcepath\music\
DEST;FLAC;112;2;\\destpath\music\
最佳答案
与其依赖于让您的值落在字符串拆分操作的正确索引处,不如创建您自己的 ConfigurationSection
定义。
参见 How To on MSDN和 MSDN ConfigurationProperty example .
这里有一些代码可以帮助您入门:
class CustomConfig : ConfigurationSection
{
private readonly CustomElementCollection entries =
new CustomElementCollection();
[ConfigurationProperty("customEntries", IsDefaultCollection = true)]
[ConfigurationCollection(typeof(CustomElementCollection), AddItemName = "add")]
public CustomElementCollection CustomEntries { get { return entries; } }
}
class CustomElementCollection : ConfigurationElementCollection
{
public CustomElement this[int index]
{
get { return (CustomElement) BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
protected override ConfigurationElement CreateNewElement()
{
return new CustomElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((CustomElement)element).Name;
}
}
class CustomElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return this["name"] as string; }
set { this["name"] = value; }
}
[ConfigurationProperty("direction", IsRequired = true)]
public string Direction
{
get { return this["direction"] as string; }
set { this["direction"] = value; }
}
[ConfigurationProperty("filePath", IsRequired = true)]
public string FilePath
{
get { return this["filePath"] as string; }
set { this["filePath"] = value; }
}
}
一旦指定了自定义配置,您就可以使用自定义 ConfigurationElement
中指定的任何属性通过 lambda 来Select
。
关于具有分隔值的多个值的 C# app.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10691063/