Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - app config doesn't change

Tags:

c#

app-config

I want to save some settings on a config file for future use. I'm trying to use the regular code that I see on all the tutorials -

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 config.AppSettings.Settings["username"].Value = m_strUserName;

 // I also tried - 
 //config.AppSettings.Settings.Remove("username");
 //config.AppSettings.Settings.Add("username", m_strUserName);

 config.Save(ConfigurationSaveMode.Modified);
 ConfigurationManager.RefreshSection("appSettings");

Now - I can see that on runtime - the file "...vshost.exe.config" on "Debug" folder is changes, nut when I close my application - all the changes are deleted. What can I do?

like image 867
TamarG Avatar asked Jul 15 '12 08:07

TamarG


2 Answers

To test using the normal exe's config file un-check the box for "Enable the Visual Studio Hosting Process" in the "Debug" tab in the project properties menu. That will make visual studio no-longer use the vshost.exe file to launch and the correct config file will be used.

enter image description here

like image 68
Scott Chamberlain Avatar answered Sep 17 '22 06:09

Scott Chamberlain


When you deploy your application to your end users, there is no vshost.config.
Your changes will be applied to the real exe.config. So you don't have to worry for this.

When you build your application in a debug session, the app.config file, present in your project, gets copied over to the output directory. Then this config file gets copied to vshost.config as well. In this way the contents of app.config overwrites any changes made during a debug session in the vshost.exe.config.

However let me say that writing this kind of information into an application config is a bad practice. The configuration file should be used only to store permanent configuration that usually don't change during the lifetime of your application. Connection settings, for example, are valid info to store there because you normally don't change these and you don't want to hard code them.

Settings like the user name should use user.config instead. This config is per-user/per-app and allows read/write access.

like image 43
Steve Avatar answered Sep 19 '22 06:09

Steve