- 不 -
NameValueSectionHandler 不会帮助用户“创建”将写入 app.config 文件的 Xml。
启动反射器并查看 System.Configuration.NameValueSectionHandler 上的以下方法:内部静态对象 CreateStatic(objectparent, XmlNode section, string keyAttriuteName, string valueAttributeName)。
来自 Microsoft 在线社区支持的 Linda Liu 在 EggHeadCafe 论坛的讨论中提供了一些有关 NameValueSectionHandler、IConfigurationSectionHandler 以及为什么从 Configuration.GetSection(string) 返回 DefaultSection 实例的重要信息:System.Configuration.Configuration 的向后兼容性.
从技术上讲,读取和创建此信息是可行的,但我建议您不要通过在配置 API 的极低级别进行交互而给自己带来更多痛苦。请使用以下代码教育性仅供参考。我强烈鼓励您使用其中一种方法,例如Richard提到使用声明式样式创建自定义 ConfigurationSection
应用程序配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="SingleTag" type="System.Configuration.SingleTagSectionHandler"/>
</configSections>
<SingleTag scheme="https" server="webmail.contoso.com" domain="CONTOSO" username="jdoe" password="iTz@s3Cr3t!"/>
</configuration>`
You could阅读此配置部分,但这对您的心理健康不利。
示例 C# 代码- 将其粘贴到 void Main(string[] args) 中并吸烟。
// Read configuration
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection readableSection = config.GetSection("SingleTag");
string readableSectionRawXml = readableSection.SectionInformation.GetRawXml();
XmlDocument readableSectionRawXmlDocument = new XmlDocument();
readableSectionRawXmlDocument.Load(new StringReader(readableSectionRawXml));
SingleTagSectionHandler readableSectionHandler = new SingleTagSectionHandler();
Hashtable result = (Hashtable)readableSectionHandler.Create(null, null, readableSectionRawXmlDocument.DocumentElement);
foreach (string item in result.Keys)
{
Console.WriteLine("{0}\t=\t{1}", item, result[item]);
}
// Create similar configuration section
Hashtable mySettings = new Hashtable();
mySettings.Add("key1", "value1:" + DateTime.Now);
mySettings.Add("key2", "value2:" + DateTime.Now);
mySettings.Add("key3", "value3:" + DateTime.Now);
mySettings.Add("keynull", null);
mySettings.Add("key4", "value4:" + DateTime.Now);
string rawData = string.Empty;
XmlDocument writableSectionXmlDocument = new XmlDocument();
XmlElement rootElement = writableSectionXmlDocument.CreateElement("CreateSingleTag");
foreach (var item in mySettings.Keys)
{
if (mySettings[item] != null)
{
rootElement.SetAttribute(item.ToString(), mySettings[item].ToString());
}
}
writableSectionXmlDocument.AppendChild(rootElement);
if (config.Sections.Get("CreateSingleTag") == null)
{
ConfigurationSection writableSection = new DefaultSection();
writableSection.SectionInformation.SetRawXml(writableSectionXmlDocument.OuterXml);
config.Sections.Add("CreateSingleTag", writableSection);
}
else
{
config.Sections["CreateSingleTag"].SectionInformation.SetRawXml(writableSectionXmlDocument.OuterXml);
}
config.Save();
为了完整起见 -
你需要以下用法
using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Xml;
以及至少对以下程序集的引用
System
System.Configuration
System.Xml