6

I am using .NET 4.0 and I would like to use the app.config file to store same parameter settings. I do the following. I use the Settings tab in the project properties to create my parameters.

This add the information in the app.config file like this:

<MyApp.Properties.Settings>
      <setting name="param1" serializeAs="String">
        <value>True</value>
      </setting>
<MyApp.Properties.Settings>

In my view model (in my code) I can access to the information in this way:

bool myBool = MyApp.Properties.Default.param1;

When I try to change the value in the config file, I try this:

Properties.Settings.Default.param1 = false;

But this causes an error, that param1 is read-only.

So how can I update my config file from my code?

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    May be try this: http://stackoverflow.com/questions/1357240/change-the-value-in-app-config-file-dynamicallay – Hari Gillala Nov 08 '12 at 10:17
  • In this solution they use config.AppSettings. AppSettings is not deprecated? I would like to use ApplicationSettings, because this use typed parameters. – Álvaro García Nov 08 '12 at 11:19
  • edited my answer with EDIT2 giving a link to an answer which link to a code which could be your solution :) – il_guru Nov 09 '12 at 13:55

4 Answers4

11

Here's my function to update or add an entry into the app.config for "applicationSettings" section. There might be a better way, but this works for me. If anyone can suggest a better method please share it, we'll always looking for something better.

    static string APPNODE = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
    static DateTime now = DateTime.Now;
    Utilities.UpdateConfig(APPNODE, "lastQueryTime", now.ToString());

    static public void UpdateConfig(string section, string key, string value)
    {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        ClientSettingsSection applicationSettingsSection = (ClientSettingsSection)config.SectionGroups["applicationSettings"].Sections[section];
        SettingElement element = applicationSettingsSection.Settings.Get(key);

        if (null != element)
        {
            applicationSettingsSection.Settings.Remove(element);
            element.Value.ValueXml.InnerXml = value;
            applicationSettingsSection.Settings.Add(element);
        }
        else
        {
            element = new SettingElement(key, SettingsSerializeAs.String);
            element.Value = new SettingValueElement();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            element.Value.ValueXml = doc.CreateElement("value");

            element.Value.ValueXml.InnerXml = value;
            applicationSettingsSection.Settings.Add(element);
        }

        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("applicationSettings");            
    }
Manny
  • 1,034
  • 1
  • 11
  • 16
5

Well, I read the link of Hari Gillala, in which one user suggested to edit directly the app.config file, that is a xml file.

So in project properties-->settings I create the parameters that I need. Then, to load a parameter in code I do the following:

_myViewModelProperty = MyApp.Properties.Settings.Default.MyParam1;

In this way, I can read easily the information of the config parameter. Is typed, so in disign time I can see if the asign is correct or not.

To update de config file, I edit the app.config file with the xml libraries of .NET.

    System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
    xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    System.Xml.XmlNode node;
    node = xml.SelectSingleNode("configuration/applicationSettings/MyApp.Properties.Settings/setting[@name='myparam1']");
    node.ChildNodes[0].InnerText = myNewValue;
    xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

In this way, I create a xml document (xml variable) and load the information of the app.config file. Then, I search for the node that I want to update, update its information (InnerText property) and finally I save the changes.

In this way, I can update the app.config. It is what I want, because in a portable application, only one user will use it, and I want that the configuration is applied in any computer in which I run the application.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
3

You should use Properties.Settings to perform this action. You can look at this documentation for more information.

//modify
Properties.Settings.Default.param1 = false;
//save the setting
Properties.Settings.Default.Save();

Note that if your settings have the Scope of User, which they must be to be writeable, then the properties are saved somewhere else and not in your local config file. See here for the details.

EDIT after discussion in comment and further searches:

My suggestion to achieve the desired result would be to switch to AppSettings. That is because, after some searches, i found out that appsettings changes the .config file in the Application Data folder (running some tests on my machine confirm that).

Look at comment in the answer to this question .

I am not sure if there is some work around, but if you want your application to have a portable app.config file, i think the only way is to switch to AppSettings which i'm sure can save changes in the app.config found in the program folder.

EDIT 2: Possible solution

I found out a possible solution to make your app portable! You can change the Provider used by Settings to save the application's settings creating a custom Provider.

The answer to this question provide a link to a code to make applicationsettings portable. I think you give it a try

Matthew
  • 1,630
  • 1
  • 14
  • 19
il_guru
  • 8,383
  • 2
  • 42
  • 51
  • 1
    Well, really I use this way, Properties.Settings.Default, but I write wrong my code. In this way is how I get the error. – Álvaro García Nov 08 '12 at 10:58
  • I think that the scope of your Setting is Application, you have to change it to User to be able to modify it at runtime – il_guru Nov 08 '12 at 11:10
  • In the app.config you could do it moving the setting from the ... section to the section, or using the GUI there's a Scope combobox in settings configuration – il_guru Nov 08 '12 at 11:15
  • yes, if the scope is user instead of application, this works. But this update the app.config that there are in the application folder? because I would like to update this app.config, because I want a portable app. – Álvaro García Nov 08 '12 at 11:25
  • Yes, it should update the app.config you read when the application started – il_guru Nov 08 '12 at 11:28
  • 1
    I try to use this way but the file myApp.exe.config is not update. But I restar my application, the changes is used, so I think that the configuration is saved in other place, but there is no other files in my program folder. – Álvaro García Nov 08 '12 at 11:36
  • I try this application in other computer and the changes made in the first computer is not applied. – Álvaro García Nov 08 '12 at 11:42
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19280/discussion-between-daimroc-and-il-guru) – Álvaro García Nov 08 '12 at 11:55
  • 1
    I'v tried it and i got the same result. I do not exactly know where it saves it... Why don't you move to AppSettings using ConfigurationManager? – il_guru Nov 08 '12 at 12:07
  • Well, if I am not wrong, appSettings is the old version, and applicationSettings is the new version. I know how to use appSettings, but I would like to use ApplicationSettings. One of the reasons is that allow typed parameters in the config file. – Álvaro García Nov 08 '12 at 16:09
  • I editet the question to add an answer because were too messy to add it here. Also applicationSettings is old too (with old i mean present in older versions) but i have to admit i do not now if one or the other is deprecated. – il_guru Nov 08 '12 at 16:26
2

Mark your setting as usersetting.

Detailed article: http://www.codeproject.com/Articles/25829/User-Settings-Applied

J. Steen
  • 15,470
  • 15
  • 56
  • 63
bitsmuggler
  • 1,689
  • 2
  • 17
  • 30