6

I'm trying to change in runtime one key of my applications settings file, but it does not work.

I do on that way:

ConfigurationSettings.AppSettings["XPTO"] = "HELLO";

It seems that it only changes in memory, not on the file.

Does anyone knows how to do this?

Thanks.

Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
rpf
  • 3,612
  • 10
  • 38
  • 47

3 Answers3

11

Take a look at my overview of .NET settings files...In short, I think you want a user-scoped setting. It will behave more like you expect.

Edit: If you are using the settings designer in Visual Studio, then simply change the "Scope" to "User". If not, you should be able to do the equivalent programmatically.

Community
  • 1
  • 1
el2iot2
  • 6,428
  • 7
  • 38
  • 51
  • 2
    Please note that when changing the Settings and saving, the settings won't be changed in the bin folder, but in [userfolder]\Local Settings\Application Data\\[company name]\\[application].exe[hash string]\\[version]\user.config – Jader Dias Oct 20 '09 at 00:02
  • 1
    In more recent versions of Windows it will be changed on [userfolder]\AppData\Local\\[company name]\\[application].exe[hash string]\\[version]\user.config – Jader Dias Oct 20 '09 at 00:03
  • @Jader Yep. I do mention this briefly in my overview and give programmatic ways to retrieve the resulting path. But thanks for sharing these details. – el2iot2 Oct 20 '09 at 18:34
6

Assuming your app has write permissions on the file...



    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  // the config that applies to all users
    AppSettingsSection appSettings = config.AppSettings;

    if (appSettings.IsReadOnly() == false)
    {
        appSettings("Key").Value = "new value";

        config.Save();
    }

I'm ignoring all the possible exceptions that can be thrown...

Joe
  • 41,484
  • 20
  • 104
  • 125
  • How can I hava access to ConfigurationManager class. I try to use this piece of code and it results in some errors that does not konws that class :S. – rpf Feb 18 '09 at 12:17
  • 2
    Add System.Configuration as a reference. – Joe Feb 18 '09 at 15:35
5

The AppSettings file is not designed to be writable. It is designed to store configurations that will not change at run time but might change over time ie: DB Connection Strings, web service URL's, etc.

So, while it may be possible to update the file in reality you should re-asses if this value should be stored there.

brendan
  • 29,308
  • 20
  • 68
  • 109