mattruma
mattruma

Reputation: 16687

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

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.

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.

Upvotes: 14

Views: 54200

Answers (9)

Dave
Dave

Reputation: 81

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... ;-) !

Upvotes: 6

Peg
Peg

Reputation: 41

I had the same problem until I realized I was running the app in debug mode, therefore my new appSetting's key was being written to the [applicationName].vshost.exe.config file.

And this vshost.exe.config file does NOT retain any new keys once the app is closed -- it reverts back to the [applicationName].exe.config file's contents.

I tested it outside of the debugger, and the various methods here and elsewhere to add a configuration appSetting key work fine. The new key is added to:[applicationName].exe.config.

Upvotes: 4

sumit
sumit

Reputation: 19

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

Upvotes: 1

esiliezar
esiliezar

Reputation:

 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

Upvotes: 3

mattruma
mattruma

Reputation: 16687

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.

Upvotes: 12

Jay S
Jay S

Reputation: 7994

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>

Upvotes: 2

thijs
thijs

Reputation: 3465

Your answer is probably here: Simplest way to have a configuration file in a Windows Forms C# Application

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532625

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.

Upvotes: 2

Fredrik Jansson
Fredrik Jansson

Reputation: 3814

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

Upvotes: 2

Related Questions