Share via


How to change application configuration file's values programmatically in c#.net 2005?

Question

Tuesday, September 8, 2009 8:04 AM | 1 vote

I am developing a WINDOWS APPLICATION using C#.Net 2005. 

Here I want to use a configuration file to store some setting in keys.

I know how to read these keys from configuration file but when I try to wrtie in it I get error.

Procedure that I followed-

I added one Application Configuration File To my project.

Which contains two keys in appSettings -

TimeFormat value =0

Port value =COM1

Now I want code to change values of these keys.

All replies (9)

Tuesday, September 8, 2009 9:27 AM ✅Answered | 2 votes

Open the configuration, make your changes, save.

static void Main(string[] args)
{
    string configPath = Path.Combine(System.Environment.CurrentDirectory, "CommunitySandbox.exe");
    Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
    DisplayConfigSetting(config);
    ModifyConfigSetting(config);
    DisplayConfigSetting(config);

    Console.WriteLine("\nMethod has returned. Press any key to exit...");
    Console.ReadLine();
}

static void ModifyConfigSetting(Configuration config)
{
    int currentValue = int.Parse(config.AppSettings.Settings["sandbox.sample"].Value);
    currentValue++;
    config.AppSettings.Settings["sandbox.sample"].Value = currentValue.ToString();
    config.Save();
}

static void DisplayConfigSetting(Configuration config)
{
    Console.WriteLine(config.AppSettings.Settings["sandbox.sample"].Value);
}

Hope that helps.

ps: consider backing up the current file before overwriting it.


Wednesday, September 9, 2009 11:32 AM ✅Answered

Hi Harsh,

Ideally, if your initial question as been answered you should mark it. If you have further questions you should start a new thread. That way it's easier for anyone else with the same question to beneit.

Adding new items is relatively simple: use the Add method of the Settings collection.

static void AddNewConfigSetting(Configuration config, string key, string value)

{

    config.AppSettings.Settings.Add(key, value);

    config.Save();

}


Tuesday, September 8, 2009 9:42 AM

Can you share the code to change the values of the key??
What is the error that you are getting??

anyways you can try this :

System.Configuration.Configuration config =  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Port Value"].Value = "<<New Value>>";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

-Paras


Tuesday, September 8, 2009 10:28 AM

Try with the following code:

public static string ReadSetting(string key)

        {

            return System.Configuration.ConfigurationSettings .AppSettings[key];

        }

 

        private void WriteSetting(string key, string value)

        {

            // load config document for current assembly

            XmlDocument doc = loadConfigDocument();

 

            // retrieve appSettings node

            XmlNode node = doc.SelectSingleNode("//appSettings" );

 

            if (node == null )

                throw new InvalidOperationException ("appSettings section not found in config file." );

 

            try

            {

                // select the 'add' element that contains the key

                XmlElement elem = (XmlElement )node.SelectSingleNode(string .Format("//add[@key='{0}']" , key));

 

                if (elem != null )

                {

                    // add value for key

                    elem.SetAttribute("value" , value);

                }

                else

                {

                    // key was not found so create the 'add' element

                    // and set it's key/value attributes

                    elem = doc.CreateElement("add" );

                    elem.SetAttribute("key" , key);

                    elem.SetAttribute("value" , value);

                    node.AppendChild(elem);

                }

                doc.Save(getConfigFilePath());

            }

            catch

            {

                throw ;

            }

        }

        private XmlDocument loadConfigDocument()

        {

            XmlDocument doc = null ;

            try

            {

                doc = new XmlDocument ();

                doc.Load(getConfigFilePath());

                return doc;

            }

            catch (System.IO.FileNotFoundException e)

            {

                throw new Exception ("No configuration file found." , e);

            }

        }

 

        private string getConfigFilePath()

        {

            return Assembly .GetExecutingAssembly().Location + ".config" ;

        }

 

 

 

  // read the Test1 value from the config file

            string test1 = ReadSetting("Test1" );

 

            //To read the settings from the config, use the following code:

 

            // read the Test1 value from the config file

            string test1 = ReadSetting("Test1" );

 

            // write a new value for the Test1 setting

            WriteSetting("Test1" , "This is my new value" );


Tuesday, September 8, 2009 11:59 AM

thanks for quick reply..
if you can explain it further?


Wednesday, September 9, 2009 7:53 AM

ok. thanks.

Firstly I was writing code like -

System.Configuration.ConfigurationSettings .AppSettings.Set("key","value");

Thats why I was getting error.


Wednesday, September 9, 2009 9:37 AM

Hi Wole Ogunremi,

            Code posted by you is working. I can read and modify existing keys.

 Now can you please tell me how to add new key via coding.


Wednesday, September 9, 2009 1:28 PM

making modification,trying to use the configuration file getting system clash for me. i don't know whether it is my system problem or other case. Any one can tell me, can i use to acess the  configuration file through C# program..?


Thursday, June 17, 2010 6:53 AM

hi

Well this is not permanantly changing my app.config which my requirement is.

Next time I start my application it again has the old entries.

Regards

Mitesh