我尝试了两种单独的方法从C#项目中的app.config中读取密钥。第一次失败:
Dictionary<string, string> s = (ConfigurationManager.GetSection("appSettings") as Hashtable)
.Cast<DictionaryEntry>()
.ToDictionary(n => n.Key.ToString(), n => n.Value.ToString());
此消息的来源是here。调试之后,我发现ConfigurationManager.GetSection("testSectionGroup/testSection")
可以正常工作,但是将其强制转换为哈希表却给了我null。我对此进行了深入研究,找到了this解决方案:
Hashtable hashSettings = new Hashtable((from key in ConfigurationManager.AppSettings.Keys.Cast<string>()
let value = ConfigurationManager.AppSettings[key]
select new { key, value }).ToDictionary(x => x.key, x => x.value));
这对于基本键很好用(即使它是哈希表而不是字典)。我确实想知道是否有办法将其转换为字典,但这不是我的主要问题。我现在遇到的问题是在app.config中创建自定义部分(到目前为止,我所拥有的设置都与SQL连接字符串相关,因此我希望将它们分组在一起,并与稍后可能添加的其他设置分开)
我找到了有关如何进行here的MS文章,但是当我尝试实现它时,却发现配置初始化失败。
这是类定义,我从here获得了帮助:
public class testSection : ConfigurationSection
{
[ConfigurationProperty("", IsRequired =true, IsDefaultCollection =true)]
public testSectionInstanceCollection Instances
{
get { return (testSectionInstanceCollection)this[""]; }
set { this[""] = value; }
}
public class testSectionInstanceCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
//throw new NotImplementedException();
return new testSectionInstanceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
//throw new NotImplementedException();
return ((testSectionInstanceElement)element).key;
}
}
public class testSectionInstanceElement : ConfigurationElement
{
[ConfigurationProperty("key", IsKey =true, IsRequired =true)]
public string key
{
get { return (string)base["key"]; }
set { base["key"] = value; }
}
[ConfigurationProperty("value", IsRequired =true)]
public string value
{
get { return (string)base["value"]; }
set { base["value"] = value; }
}
}
}
这是我现在的app.config文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
<appSettings>
<add key="Data Source" value="localhost\SQLEXPRESS"/>
<add key="Initial Catalog" value="(empty)"/>
<add key="Integrated Security" value="SSPI"/>
</appSettings>
<configSections>
<sectionGroup name = "testSectionGroup">
<section name="test" type="mssql_gui.testSection" allowLocation="true" allowDefinition="Everywhere"/>
</sectionGroup>
</configSections>
<testSectionGroup>
<testSection>
<add key="test key" value="test value"/>
</testSection>
</testSectionGroup>
</configuration>
除了解决“配置初始化失败”错误之外,我还需要找到一种方法来使第一个字典解决方案正常工作(从我引用的第一篇文章中),因为我能够使用的第二个解决方案专门处理ConfigurationManager.AppSettings,而不是像允许我在参数中指定自定义部分,就像ConfigurationManager.GetSection(...)。
Here this the git for the project,如果有帮助或有兴趣的人。