Home > Backend Development > C++ > How Can I Persistently Change App.Config Values in C#?

How Can I Persistently Change App.Config Values in C#?

Linda Hamilton
Release: 2025-01-01 01:53:10
Original
486 people have browsed it

How Can I Persistently Change App.Config Values in C#?

Changing App.Config Values

Problem:

An attempt to modify a key-value pair in the App.Config using System.Configuration.ConfigurationManager.AppSettings.Set does not persist the change to the configuration file.

Code:

lang = "Russian";
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
     System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);
}
Copy after login

Reason:

AppSettings.Set only modifies the configuration settings in memory; it does not update the actual configuration file.

Solution:

To persist the changes, use the UpdateSetting function:

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}
Copy after login

Note:

  • When debugging, build the project and launch the executable from the output directory, as Visual Studio overwrites the App.Config file during debugging.
  • To verify the changes, open the YourApplicationName.exe.config file in the output directory.

The above is the detailed content of How Can I Persistently Change App.Config Values in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template