8 Jul 2011

Write and Delete Settings to .NET App.Config or Web.Config

I don’t have anything to post Where, but I think this might be useful for you. Want to write and delete appSettings in App.Config or Web.Config? Sure you do know how to read it.

Hope this little code helps

Code Snippet
  1. namespace Rdz.Utility
  2. {
  3.     public static class ConfigUtility
  4.     {
  5.         /// <summary>
  6.         /// Writes to configuration file (App.Config) to specified key, or creates a new Key if doesn't exist
  7.         /// </summary>
  8.         /// <param name="KeyName">The Application Settings KeyName</param>
  9.         /// <param name="Value">The Application Settings Value</param>
  10.         public static void WriteToAppConfig(string KeyName, string Value)
  11.         {
  12.             Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  13.             if (cfg.AppSettings.Settings.AllKeys.Contains(KeyName))
  14.                 cfg.AppSettings.Settings[KeyName].Value = Value;
  15.             else
  16.                 cfg.AppSettings.Settings.Add(KeyName, Value);
  17.             cfg.Save(ConfigurationSaveMode.Modified);
  18.             ConfigurationManager.RefreshSection("appSettings");
  19.         }
  20.  
  21.         /// <summary>
  22.         /// Deletes specified key in app.config
  23.         /// </summary>
  24.         /// <param name="KeyName"></param>
  25.         public static void DeleteAppConfig(string KeyName)
  26.         {
  27.             Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  28.             if (cfg.AppSettings.Settings.AllKeys.Contains(KeyName))
  29.             {
  30.                 cfg.AppSettings.Settings.Remove(KeyName);
  31.                 cfg.Save(ConfigurationSaveMode.Modified);
  32.             }
  33.             ConfigurationManager.RefreshSection("appSettings");
  34.         }
  35.     }
  36. }

Cheers… and happy coding! Hihi...

Tidak ada komentar:

Posting Komentar

[give me your ideas, hopes, comments and compliments below...]
[aaand...... +1 if you need to....]