Deserializing web.config custom sections using the classes generated by XSD
I Have a custom section in Web.Con开发者_如何学JAVAfig file and referring another .config file through configSource. I have generated .cs file using the XSD for my schema. How to use my generated classes to deserialize the config. When I try to load the configsection using .GetSection() method, it gives me error that the class should implement from ConfigurationSection. Since I have generated the classes using xsd, they were not inherited from ConfigurationSection or ConfigurationElement. Thanks in advance!!
I have implemented the class from ConfigurationSection to get the file name and using XMLSerializer to Deserialize using the classes generated by XSD tool. Here is sample:
namespace mycontrol
{
public class ConfigurationSection : System.Configuration.ConfigurationSection
{
//Configuration is the type generated by XSD for my schema element Configuration
private static Configuration _config;
/// <summary>
/// static method to load config section and deserialize config
/// </summary>
/// <returns></returns>
private static Configuration GetConfig()
{
if (_config == null)
{
ConfigurationSection configSection = (ConfigurationSection)ConfigurationManager.GetSection("SearchControlsConfig") as ConfigurationSection;
if (!string.IsNullOrEmpty(configSection.ExternalConfigSource))
{
string strFilePath = configSection.ExternalConfigSource;
if (!File.Exists(strFilePath))
{
strFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strFilePath);
if (!File.Exists(strFilePath))
return null;
}
using (FileStream fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
XmlSerializer config = new XmlSerializer(typeof(Configuration));
_config = (Configuration)config.Deserialize(fs);
}
}
}
return _config;
}
/// <summary>
/// Attribute to specify config source file in custom config section
/// </summary>
[ConfigurationProperty("externalConfigSource", DefaultValue = "", IsRequired = false)]
public string ExternalConfigSource
{
get
{
return this["externalConfigSource"] as string;
}
}
}
}
I cannot use the configSource attribute as my property while specifying the custom config, because it is reserved by ConfigurationManager.
精彩评论