Saturday, July 4, 2020

c# - App.config - read and write - easy way

Let's discuss about how we can read and write App.Config file in a easy way. Before that if you need to know more about what is this file, read this post https://blog.submain.com/app-config-basics-best-practices/

Lets get back to code.

     public static bool UpdateAppSettings(string key, string value)  
     {  
       try  
       {  
         var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
         var settings = configFile.AppSettings.Settings;  
         if (settings[key] == null)  
         {  
           settings.Add(key, value);  
         }  
         else  
         {  
           settings[key].Value = value;  
         }  
         configFile.Save(ConfigurationSaveMode.Modified);  
         ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);  
         return true;  
       }  
       catch (Exception)  
       {  
         throw;  
       }  
     }  

     public static string ReadAppSetting(string key)  
     {  
       try  
       {  
         return ConfigurationManager.AppSettings[key];  
       }  
       catch (Exception)  
       {  
         throw;  
       }  
     }  


UpdateAppSettings and ReadAppSetting are two methods we use. lets say we have a config value like below.



We can read and update this values as this.


 public static string ConString { get { return ReadAppSetting("ConString"); } set { UpdateAppSettings("ConString", value); } }  


Hope you can get this applied to your need too.
Happy coding.

No comments:

Post a Comment