ExampleConfigurationSectionHandler

ExampleConfigurationSectionHandler.cs

 using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization; namespace SampleConfigSectionHandle
{
public sealed class ExampleConfigurationSectionHandler : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
var xmlSerializer = new XmlSerializer(typeof(UserInfo)); using (var stream = new MemoryStream(Encoding.Default.GetBytes(section.InnerXml)))
{
var xmlNode = XmlReader.Create(stream); return xmlSerializer.Deserialize(xmlNode);
}
}
} public class UserInfo
{
public string UserName { get; set; } public string UserPwd { get; set; }
}
}

App.config

 <?xml version="1.0" encoding="utf-8" ?>
<configuration> <configSections> <!--示例配置节-->
<section name="example" type="SampleConfigSectionHandle.ExampleConfigurationSectionHandler,SampleConfigSectionHandle"/> </configSections> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup> <!--配置节实例-->
<example> <UserInfo>
<UserName>WangYa</UserName>
<UserPwd>123456</UserPwd>
</UserInfo> </example> </configuration>

Program.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace SampleConfigSectionHandle
{
class Program
{
static void Main(string[] args)
{
var config = ConfigurationManager.GetSection("example") as UserInfo; if (config != null)
{
Console.WriteLine(config.UserName);
Console.WriteLine(config.UserPwd);
} Console.Read();
}
}
}
上一篇:【ThinkingInC++】61、非成员运算符


下一篇:20155207王雪纯 《Java程序设计》实验一报告