views:

5732

answers:

7

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 no really update the settings value. Seems I have to view the project properties when I make a change and then recompile.

  • I'm wondering ... what is the best and easiest way to handle customizable settings for a project -- thought this would be a no-brainer with how .Net handles it ... shame on me.

  • Is it possible to use one of the settings, AppSettings, ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Gives me a read-only error when I compile.

+1  A: 

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>
Jay S
Do you have a code snippet on how to add your own section?
mattruma
I've always edited the app.config directly. I just placed the snippet above into the app.config. The 'section' line in the configSections block defines your own section.
Jay S
My mistake, I misunderstood your question. I thought you were trying to configure the app, not dynamically configure the app via the UI.
Jay S
+2  A: 

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();

Fredrik Jansson
I get a read-only error when I try to do this ... please see my example in the question.
mattruma
Is your properties file set to read-only?
Jay S
It has to be a user setting: <userSettings> <ConsoleApplication1.Properties.Settings> <setting name="StringSetting" serializeAs="String"> <value>AValue</value> </setting> </ConsoleApplication1.Properties.Settings> </userSettings>
Fredrik Jansson
+2  A: 

How are you referencing the Settings class in your code? Are you using the default instance or creating a new Settings object? I believe that the default instance uses the designer generated value which is re-read from the configuration file only when the properties are opened. If you create a new object, I believe that the value is read directly from the configuration file itself rather from the designer-generated attribute, unless the setting doesn't exist in the app.config file.

Typically my settings will be in a library rather than directly in the application. I set valid defaults in the properties file. I can then override these by adding the appropriate config section (retrieved and modified from the library app.config file) in the application's configuration (either web.config or app.config, as appropriate).

Using:

 Settings configuration = new Settings();
 string mySetting = configuration.MySetting;

instead of:

 string mySetting = Settings.Default.MySetting;

is the key for me.

tvanfosson
A: 

Your answer is probably here: http://stackoverflow.com/questions/114527/simplest-way-to-have-a-configuration-file-in-a-windows-forms-c-application

thijs
I'd like them to be editable.
mattruma
+3  A: 

This is silly ... and I think I am going to have to apologize for wasting everyone's time! But it looks like I just need to set the scope to User instead of Application and I can the write the new value.

mattruma
Yes. Application settings are settings that are rarely changed, and should only be modified by an administrator. User settings are settings that may be modified by users, on a per-user basis. :) Glad you figured it out! :)
Greg D
+2  A: 
 System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        config.AppSettings.Settings["oldPlace"].Value = "3";     
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

Try with this code , is easy.

Atte: Erick Siliezar

A: 

Try this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
   <!--- ->
  </configSections>

  <userSettings>
   <Properties.Settings>
      <setting name="MainFormSize" serializeAs="String">
        <value>
1022, 732</value>
      </setting>
   <Properties.Settings>
  </userSettings>

  <appSettings>
    <add key="TrilWareMode" value="-1" />
    <add key="OptionsPortNumber" value="1107" />
  </appSettings>

</configuration>

Reading values from App.Config File:

//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private int LoadConfigData ()
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        // AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
        // points to the config file.   
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        int smartRefreshPortNumber = 0;
        foreach (XmlNode node in doc.ChildNodes.Item(1))
        {
        //Searching for the node “”
            if (node.LocalName == "appSettings")
            {
                 smartPortNumber =Convert.ToInt32(node.ChildNodes.Item(1).Attributes[1].Value);
            }
        }
        Return smartPortNumber;
    }

Updating the value in the App.config:

//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private void UpdateConfigData()
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);


        //Looping through all nodes.
        foreach (XmlNode node in doc.ChildNodes.Item(1))
        {
        //Searching for the node “”
            if (node.LocalName == "appSettings")
            {
                if (!dynamicRefreshCheckBox.Checked)
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = this.portNumberTextBox.Text;
                }
                else
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = Convert.ToString(0);
                }
            }
        }
        //Saving the Updated values in App.config File.Here updating the config
        //file in the same path.
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }
sumit