asp. net code to modify the web. config node

  • 2020-06-15 08:00:33
  • OfStack

However, this variable does not have a fixed value, it will change according to the actual situation, such as the need to read a configuration file path, and this path is the site published the actual hard disk path, if it is directly compiled state, no problem. But if site iis changes paths, you need to modify the parameters in this ES1en.config. It would be more reasonable and convenient to change this compile-time state to the run-time state. This requires a solution that dynamically modifies web.config in code.
code

  /// <summary>
          ///  write web.config
          /// </summary>
          /// <param name="item">appSettings Etc. </param>
          /// <param name="key"> key </param>
          /// <param name="value"> value </param>
          public void WriteConfig(string item, string key, string value)
          {
              if (item == "")
             {
                 item = "appSettings";
             }
             Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
             AppSettingsSection appSection = (AppSettingsSection)config.GetSection(item);
             if (appSection.Settings[key] == null)
             {
                 appSection.Settings.Add(key, value);
                 config.Save();
             }
             else
             {
                 appSection.Settings.Remove(key);
                 appSection.Settings.Add(key, value);
                 config.Save();
            }
         } 

Related articles: