我遵循一個關於Stackoverflow的教程來將自定義配置節添加到我的exe配置文件中,但是在調用它時,它將返回null。它甚至沒有進入靜態構造函數,所以有些東西顯然是錯誤的,但我看不到。無法獲取自定義配置節在app.config中工作
這是我的配置文件和我希望找到的部分。
<configuration>
<appSettings>
</appSettings>
<configSections>
<section name="PresetFilters" type="ImageTool.PresetFiltersConfiguration, ImageTool" />
</configSections>
<PresetFilters>
<add key="Default,-20,0,0,0,0" />
<add key="No Change,0,0,0,0,0" />
<add key="Dark Photo,10,10,0,0,-10" />
</PresetFilters>
</configuration>
我這樣稱呼它:
PresetFiltersConfiguration pf = (PresetFiltersConfiguration)ConfigurationManager.GetSection("PresetFilters");
,並返回null,甚至沒有進入我的類或類靜態。這是代碼。任何幫助,將不勝感激。謝謝。
public class PresetFiltersConfiguration : ConfigurationSection
{
private static ConfigurationPropertyCollection properties;
private static ConfigurationProperty propPresets;
static PresetFiltersConfiguration()
{
propPresets = new ConfigurationProperty(null, typeof(PresetFiltersElementCollection),
null,
ConfigurationPropertyOptions.IsDefaultCollection);
properties = new ConfigurationPropertyCollection { propPresets };
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return properties;
}
}
public PresetFiltersElementCollection PresetFilter
{
get
{
return this[propPresets] as PresetFiltersElementCollection;
}
}
}
public class PresetFiltersElementCollection : ConfigurationElementCollection
{
public PresetFiltersElementCollection()
{
properties = new ConfigurationPropertyCollection();
}
private static ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
return properties;
}
}
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.BasicMap;
}
}
protected override string ElementName
{
get
{
return "add";
}
}
protected override ConfigurationElement CreateNewElement()
{
return new PresetFiltersElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
var elm = element as PresetFiltersElement;
if (elm == null) throw new ArgumentNullException();
return elm.KeyName;
}
}
public class PresetFiltersElement : ConfigurationElement
{
private static ConfigurationPropertyCollection properties;
private static ConfigurationProperty propKey;
protected override ConfigurationPropertyCollection Properties
{
get
{
return properties;
}
}
public PresetFiltersElement()
{
propKey = new ConfigurationProperty("key", typeof(string),
null,
ConfigurationPropertyOptions.IsKey);
properties = new ConfigurationPropertyCollection { propKey };
}
public PresetFiltersElement(string keyName)
: this()
{
KeyName = keyName;
}
public string KeyName
{
get
{
return this[propKey] as string;
}
set
{
this[propKey] = value;
}
}
}
您需要添加configSection,請參閱https://msdn.microsoft.com/en-us/library/2tw134k3.aspx –
謝謝,這樣做(如我的編輯),仍然沒有任何反應。 –
如果我將它移動到控制檯應用程序,它工作正常,這是一個類庫,它不起作用。它正在讀取file.dll.config文件,因爲我在配置中的其他部分工作正常。 –