问题
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>
回答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.
回答2:
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
来源:https://stackoverflow.com/questions/30640528/app-config-modify-value-c-sharp