这个问题在这里得到解决App.Config 更改值 https://stackoverflow.com/questions/11149556/c-sharp-app-config-change-value
接受的答案是
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();
但当我尝试实现相同的功能时,我发现了一个奇怪的行为。上面的答案抛出NullReferenceException
设置值时。这config.AppSettings.Settings
计数为零。
所以我将 configFile 路径设置为项目内的 app.config 路径
string configFile = @"D:\App\Schedule\Schedule\App.config";
这会修改项目内的 app.config 以及 bin/debug 中的 >.exe.config。但我认为这不是一个可行的解决方案,因为应用程序可以部署在任何路径上。因此对 configPath 进行硬编码是行不通的。
然后我再次修改了给定的 configFile
string configFile = System.IO.Path.Combine(appPath, "<appname>.exe.config");
上面的代码运行并仅修改 >.exe.config 而不是项目内的 app.config。
我真的不确定哪个是正确的,或者我错过了任何东西。
我使用的是 VS 2012,c# 4.5,它是控制台应用程序。截至目前,我的控制台中没有其他代码,app.config 是
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="YourThing" value="" />
</appSettings>
</configuration>