4

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>
Community
  • 1
  • 1
Gopi
  • 5,656
  • 22
  • 80
  • 146

2 Answers2

1

This is just a wrong understanding of app.config. You are expecting application to modify your source code which is incorrect.

When you run your program it creates a copy of app.config to your bin/debug or bin/release folder.

Your second solution is fine. Application is working as expected.

Manjoor
  • 4,091
  • 10
  • 43
  • 67
  • yes, I do understand it, but the accepted has nice way of doing the same. Why it doesn't work for me :( I see the accepted answer is more elegant than mine – Gopi Jun 04 '15 at 10:04
1
Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            config.AppSettings.Settings["PresentationFolder"].Value = path;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

Where: path - is "new value", "appSettings" - is Section in App.config

Paweł Groński
  • 567
  • 1
  • 6
  • 17