The question is addressed here App.Config change value
The accepted answer is
string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["YourThing"].Value = "New Value";
config.Save();
But when I tried to implement the same, I found a weird behavior. The above answer throws NullReferenceException
when setting the value. The config.AppSettings.Settings
count is zero.
So I set the configFile path to the app.config path inside project
string configFile = @"D:\App\Schedule\Schedule\App.config";
This modifies both app.config inside the project as well as << appname >>.exe.config which is in bin/debug. But I don't think this is a feasible solution as the application can be deployed on any path. So hard coding the configPath will not work.
Then again I modified the configFile as given
string configFile = System.IO.Path.Combine(appPath, "<appname>.exe.config");
The above code runs and modifies only the << appname >>.exe.config and not the app.config inside the project.
I am really not sure which is correct or I am missing any thing.
I am on VS 2012, c# 4.5 and it is console application. As of now there is no other code in my console and the app.config is
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="YourThing" value="" />
</appSettings>
</configuration>