Skip to content

3. Custom config file location

Emrys edited this page Jan 25, 2018 · 1 revision

In actual development, we may not put the configuration file in the default Web.config/App.config, such as configuring user information separately, and so on

1. Config

The configuration file is placed in the "/Cfg/UserInfo.config" and the content is

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="userInfo" type="Emrys.SuperConfig.Section,Emrys.SuperConfig"></section> 
  </configSections> 
  <userInfo userName="FEmrys" email="i@emrys.me" age="17">
    <blogUrl>http://www.cnblogs.com/emrys5/</blogUrl>
    <favoriteColor>Blue</favoriteColor>
    <dislikeColor>2</dislikeColor>
  </userInfo>  
</configuration>

2. Set file path

var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cfg", "UserInfo.config"); 
SuperConfig<UserInfo>.SettingFilePath(configFilePath); 

3. Get value

var user = SuperConfig<UserInfo>.Value;

Assert.AreEqual(user.UserName, "FEmrys");
Assert.AreEqual(user.Email, "i@emrys.me");
Assert.AreEqual(user.Age, 17);
Assert.AreEqual(user.BlogUrl, "http://www.cnblogs.com/emrys5/");
Assert.AreEqual(user.FavoriteColor, Color.Blue);
Assert.AreEqual(user.DislikeColor, Color.Black);

3. Remark

  1. All configuration code is best placed in the code of program startup, because SuperConfig uses caching, and all the whole program cycle can be set up before get the value. For example, in Asp.net development, you can place it in Application_Start.
protected void Application_Start()
{
    var configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cfg", "UserInfo.config"); 
    SuperConfig<UserInfo>.SettingFilePath(configFilePath);
}

Get value anywhere

var user = SuperConfig<UserInfo>.Value;