Get Configuration File As Dictionary In C#

To achieve this, we can use the following namespace: "System.Configuration". Here is a custom code snippet, where the single parameter is the sectionName. sectionName parameter will hold the section name of a configuration file which you want as key-value pair.
  1. public static Dictionary < stringstring > GetConfigFileAsDict(string sectionName) {  
  2.  Dictionary < stringstring > resultDictionary = new Dictionary < stringstring > ();  
  3.  try {  
  4.   Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
  5.   if (configuration.GetSection(sectionName) is ConfigFileSection section) {  
  6.    foreach(ConfigFileElement element in section.Settings) {  
  7.     if (element.Value != null && element.Value != "")  
  8.      resultDictionary.Add(element.Key, element.Value);  
  9.    }  
  10.   }  
  11.   
  12.  } catch (Exception e) {  
  13.   //Throw error    
  14.  }  
  15.  return resultDictionary;  
  16. }