在C#中读取自定义配置部分的键值
我需要从app / web.config中的自定义部分读取键值。
我经历了
使用ConfigurationManager从Web.Config中读取密钥
和
如何使用C#检索.config文件中的自定义配置节列表?
但是,当我们需要显式指定配置文件的路径时,它们没有指定如何读取自定义部分(在我的情况下,配置文件不在其默认位置)
我的web.config文件示例:
我需要在MyCustomTag中读取键值对。
当我尝试(configFilePath是我的配置文件的路径): –
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFilePath }; var config = ConfigurationManager.OpenMappedExeConfiguration( configFileMap, ConfigurationUserLevel.None); ConfigurationSection section = config.GetSection(sectionName); return section[keyName].Value;
我收到一条错误,指出“无法在[keyName]部分访问受保护的内部索引器’此’
不幸的是,这并不像听起来那么容易。 解决问题的方法是使用ConfigurationManager
获取文件配置文件,然后使用原始xml。 所以,我通常使用以下方法:
private NameValueCollection GetNameValueCollectionSection(string section, string filePath) { string file = filePath; System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); NameValueCollection nameValueColl = new NameValueCollection(); System.Configuration.ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = file; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); string xml = config.GetSection(section).SectionInformation.GetRawXml(); xDoc.LoadXml(xml); System.Xml.XmlNode xList = xDoc.ChildNodes[0]; foreach (System.Xml.XmlNode xNodo in xList) { nameValueColl.Add(xNodo.Attributes[0].Value, xNodo.Attributes[1].Value); } return nameValueColl; }
并调用该方法:
var bla = GetNameValueCollectionSection("MyCustomTag", @".\XMLFile1.xml"); for (int i = 0; i < bla.Count; i++) { Console.WriteLine(bla[i] + " = " + bla.Keys[i]); }
结果:
Formo让它变得非常简单,例如:
dynamic config = new Configuration("customSection"); var appBuildDate = config.ApplicationBuildDate();
请参阅配置章节中的Formo
我经常搜索以找到同样问题的解决方案。 经过一些搜索和调试,我在我的应用程序中使用了它。 我希望它也可以帮到你。