2

I want to update app. config file in windows form c# . here is a code for updating app. config

 // updating
 System.Configuration.Configuration config =  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 config.AppSettings.Settings.Remove("name");
 config.AppSettings.Settings.Add("name",txtName.Text);
 config.Save(ConfigurationSaveMode.Modified);
 ConfigurationManager.RefreshSection("appSettings");

 // show updating result on labels ( and this work fine )
 string value = ConfigurationManager.AppSettings["name"];
 lblName.Text = value;

this update work fine when I am running an application but when I restart application all config is reset to default

Muhammad Faisal
  • 135
  • 1
  • 1
  • 11
  • so there is no way to update default values ? – Muhammad Faisal Jul 02 '14 at 05:04
  • I think I got it wrong. Please check this [link](http://stackoverflow.com/questions/8522912/update-app-config-file-programatically-with-configurationmanager-openexeconfigur). – Hassan Jul 02 '14 at 05:07
  • Traditionally app.config resides in the Program Files directory with the main program, which is not writeable by standard users and therefor not writeable by your program if it is not running as an admin. Have you considered not using app.config and instead using your own settings container which saves itself in a common writeable folder like [`CommonApplicationData`](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder%28v=vs.110%29.aspx)? – Scott Chamberlain Jul 02 '14 at 05:14
  • link answers is not working :( – Muhammad Faisal Jul 02 '14 at 05:23
  • i am a beginner in windows form ! and i have no idea about CommonApplicationData . – Muhammad Faisal Jul 02 '14 at 05:24
  • is this a good practice if i use a text file for storing values ? – Muhammad Faisal Jul 02 '14 at 05:25
  • Just a thought, if you're running this using Visual Studio, the files in the bin\Debug folder (including the config file) will be overwritten when you press F5. That would make it look like it was reset to default values. – vesan Jul 02 '14 at 05:53
  • Btw you might want to take a look at this: http://msdn.microsoft.com/en-us/library/0zszyc6e(v=vs.110).aspx. As others remarked, changing values in the app.config folder is usually not the best idea. – vesan Jul 02 '14 at 05:56

1 Answers1

1

Instead of using the Configuration class, open the file as a regular Xml file and make your changes. Note that when you are doing this, when you save the file back, any Comments in your .config file will be removed by the Xml class. To prevent this, you must read ALL types of Xml nodes from the original configuration file and write them all back.