c Configuration File App. config Method for Operating Class Libraries

  • 2021-11-13 02:29:35
  • OfStack

Examples are as follows:


public class ConfigOperator
  {
    #region  Get from the configuration file Value
    /// <summary>
    ///  Get from the configuration file Value
    /// </summary>
    /// <param name="key"> In the configuration file key String </param>
    /// <returns></returns>
    public static string GetValueFromConfig(string key)
    {
      try
      {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        // Get AppSettings Node of  
        AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");
        return appsection.Settings[key].Value;
      }
      catch
      {
        return "";
      }
    }
    #endregion

    #region  Setting the configuration file 
    /// <summary>
    ///  Setting the configuration file 
    /// </summary>
    /// <param name="key"> In the configuration file key String </param>
    /// <param name="value"> In the configuration file value String </param>
    /// <returns></returns>
    public static bool SetValueFromConfig(string key, string value)
    {
      try
      {
        // Open configuration file  
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        // Get AppSettings Node of  
        AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");
        appsection.Settings[key].Value = value;
        config.Save();

        return true;
      }
      catch
      {
        return false;
      }
    }
    #endregion

Related articles: