How to edit application configuration settings? App.config best way to go?

前端 未结 9 696
攒了一身酷
攒了一身酷 2021-01-04 05:23

For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to

相关标签:
9条回答
  • 2021-01-04 05:49

    EDIT: My mistake. I misunderstood the purpose of the original question.

    ORIGINAL TEXT:

    We often setup our settings directly in the app.config file, but usually this is for our custom settings.

    Example app.config:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </configSections>
        <connectionStrings>
            <add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
        </connectionStrings>
        <MySection>
            <add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
            <add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
            <add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
        </MySection>
    </configuration>
    
    0 讨论(0)
  • 2021-01-04 05:52

    I also tried to resolved this need and I have now a nice pretty ConsoleApplication, which i want to share: (App.config)

    What you will see is:

    1. How to read all AppSetting propery
    2. How to insert a new property
    3. How to delete a property
    4. How to update a property

    Have fun!

        public void UpdateProperty(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
    
    
            // update SaveBeforeExit
            config.AppSettings.Settings[key].Value = value;
            Console.Write("...Configuration updated: key "+key+", value: "+value+"...");
    
            //save the file
            config.Save(ConfigurationSaveMode.Modified);
            Console.Write("...saved Configuration...");
            //relaod the section you modified
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
            Console.Write("...Configuration Section refreshed...");
        }
    
        public void ReadAppSettingsProperty()
        {
            try
            {
                var section = ConfigurationManager.GetSection("applicationSettings");
    
                // Get the AppSettings section.
                NameValueCollection appSettings = ConfigurationManager.AppSettings;
    
                // Get the AppSettings section elements.
                Console.WriteLine();
                Console.WriteLine("Using AppSettings property.");
                Console.WriteLine("Application settings:");
    
                if (appSettings.Count == 0)
                {
                Console.WriteLine("[ReadAppSettings: {0}]", "AppSettings is empty Use GetSection command first.");
                }
                for (int i = 0; i < appSettings.Count; i++)
                {
                    Console.WriteLine("#{0} Key: {1} Value: {2}",
                    i, appSettings.GetKey(i), appSettings[i]);
                }
            }
            catch (ConfigurationErrorsException e)
            {
                Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
            }
    
        }
    
    
        public void updateAppSettingProperty(string key, string value)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string sectionName = "appSettings";
    
    
            config.AppSettings.Settings.Remove(key);
            config.AppSettings.Settings.Add(key, value);
    
            SaveConfigFile(config);
        }
    
        public void insertAppSettingProperty(string key, string value)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string sectionName = "appSettings";
    
            config.AppSettings.Settings.Add(key, value);
    
            SaveConfigFile(config);
        }
    
        public void deleteAppSettingProperty(string key)
        {
            // Get the application configuration file.
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings.Remove(key);
    
            SaveConfigFile(config);
        }
    
        private static void SaveConfigFile(System.Configuration.Configuration config)
        {
            string sectionName = "appSettings";
    
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
    
            // Force a reload of the changed section. This  
            // makes the new values available for reading.
            ConfigurationManager.RefreshSection(sectionName);
    
            // Get the AppSettings section.
            AppSettingsSection appSettingSection =
              (AppSettingsSection)config.GetSection(sectionName);
    
            Console.WriteLine();
            Console.WriteLine("Using GetSection(string).");
            Console.WriteLine("AppSettings section:");
            Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());
        }    
    }
    

    Configuration File looks like as:

    <configuration>
    <configSections>
    </configSections>
    <appSettings>
        <add key="aNewKey1" value="aNewValue1" />
    </appSettings>
    

    Well, so I didn't have any Problems with AppSettings with this Solution! Have fun... ;-) !

    0 讨论(0)
  • 2021-01-04 05:52

    Not sure if this is what you are after, but you can update and save the setting from the app:

    ConsoleApplication1.Properties.Settings.Default.StringSetting = "test"; ConsoleApplication1.Properties.Settings.Default.Save();

    0 讨论(0)
提交回复
热议问题