Search code examples
c#configconfiguration-filesconfigurationmanager

Read Config File using AppSetting


I have stored my app settings in Config file using ConfigurationManager Class, my config file is in a Custom Path, now I want to read my config file but my Code is not working. How should I change my code?

Storing Config File (Works perfect):

static void AddUpdateAppSettings2(string key, string value)
{
    try
    {
        string _path = Application.StartupPath + "\\ss.ini";
        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap()
        {
            ExeConfigFilename = _path
        };
        Configuration configFile = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, 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);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

Reading Config File (Not working, Only works if my config file store is default path) :

static void ReadSetting(string key)
{
    try
    {
        var appSettings =ConfigurationManager.AppSettings;
        string result = appSettings[key] ?? "Not Found";
        Console.WriteLine(result);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error reading app settings");
    }
}

Solution

  • As a conversion, app.config file is always stored at application path with application_name.config name.

    If you want to store your configurations at custom path, consider using separate XML file bypassing app.config file. Following is the sample code:

    internal sealed class AppSettingsSerializer
    {
        private AppSettingsSerializer() { }
    
        static int BufferSize { get { return 4096; } }
    
        internal static AppSettings GetAppSettings(string filePath)
        {
            if(File.Exists(filePath) == false)
                return new AppSettings();
    
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(AppSettings));
            using(FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, BufferSize, FileOptions.SequentialScan))
            {
                XmlReader xmlReader = XmlReader.Create(fileStream);
                return (AppSettings)xmlSerializer.Deserialize(xmlReader);
            }
        }
    
        internal static void SetAppSettings(string filePath, AppSettings appSettings)
        {
            XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
            xmlSerializerNamespaces.Add("", "");
    
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(AppSettings));
            using(FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, BufferSize, FileOptions.WriteThrough))
            {
                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Indent = true;
                xmlWriterSettings.NewLineOnAttributes = true;
    
                XmlWriter xmlWriter = XmlWriter.Create(fileStream, xmlWriterSettings);
                xmlSerializer.Serialize(xmlWriter, appSettings, xmlSerializerNamespaces);
            }
        }
    }
    
    public sealed class AppSettings
    {
        public bool Setting1 { get; set; }
        public string Setting2 { get; set; }
    
        public AppSettings()
        {
            Setting1 = false;
            Setting2 = "localhost";
        }
    }
    

    Following is the usage:

    AppSettings appSettings = appSettings = AppSettingsSerializer.GetAppSettings(appSettingsFilePath);
    AppSettingsSerializer.SetAppSettings(appSettingsFilePath, appSettings);