62,074
社区成员
发帖
与我相关
我的任务
分享
public static class ConfigManager
{
public static WebsiteConfiguration WebSitConfig
{
get
{
return ConfigLoader.LoadConfig<WebsiteConfiguration>( );
}
}
}
this.txtSiteUrl.Text = ConfigManager.WebSitConfig.SiteUrl;
this.txtCurrentThemeName.Text = ConfigManager.WebSitConfig.ThemeConfig.DefaultThemeName;
this.themeGrid.DataSource = ConfigManager.WebSitConfig.ThemeConfig.Themes;
this.themeGrid.DataBind( );
public class ThemeConfig
{
[XmlAttribute( "defaultTheme" )]//serializable attribute
public string DefaultThemeName { get; set; }
[XmlElement( "theme" )]//serializable attribute
public ThemeCollection Themes { get; set; }
private Theme DefaultTheme
{
get { return Themes[DefaultThemeName]; }
}
}
public class Theme
{
[XmlAttribute( "name" )]//serializable attribute
public string Name { get; set; }
}
public class ThemeCollection : KeyedCollection<string, Theme>
{
protected override string GetKeyForItem(Theme item)
{
return item.Name;
}
}
internal sealed class ConfigLoader
{
private ConfigLoader() { }
public static T LoadConfig<T>() where T : class
{
return LoadConfig<T>( null );
}
public static T LoadConfig<T>(string fileName) where T : class
{
if ( string.IsNullOrEmpty( fileName ) )
{
fileName = HttpContext.Current.Server.MapPath( string.Concat( "~/", typeof( T ).Name ,".config") );
}
string cacheKey = fileName;
T configObj = HttpRuntime.Cache[cacheKey] as T;
if ( configObj == null )
{
configObj = LoadFromXml<T>( fileName );
HttpRuntime.Cache.Insert( cacheKey, configObj, new System.Web.Caching.CacheDependency( fileName ) );
}
return configObj;
}
private static T LoadFromXml<T>(string fileName) where T : class
{
FileStream fs = null;
try
{
XmlSerializer serializer = new XmlSerializer( typeof( T ) );
fs = new FileStream( fileName, FileMode.Open, FileAccess.Read );
return (T)serializer.Deserialize( fs );
}
catch ( Exception ex )
{
return null;
}
finally
{
if ( fs != null )
{
fs.Close( );
}
}
}
<?xml version="1.0"?>
<websiteConfig>
<siteUrl><![CDATA[http://huobazi.aspxboy.com/]]></siteUrl>
<themeConfig defaultTheme="Red">
<theme name="Blue" />
<theme name="Red" />
<theme name="Black" />
</themeConfig>
</websiteConfig>
namespace Huobaz.XiaHouWeni.CSDN.TestWebapplication
{
[XmlRoot( "websiteConfig" )]//serializable attribute
public class WebsiteConfiguration
{
[XmlElement("siteUrl")]//serializable attribute
public string SiteUrl { get; set; }
[XmlElement( "themeConfig" )]//serializable attribute
public ThemeConfig ThemeConfig { get; set; }
}
}