app.config修改值c#
这里提出的问题是App.Config的变化值
接受的答案是
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();
但是当我试图实现同样的function时,我发现了一种奇怪的行为。 上面的答案在设置值时抛出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, ".exe.config");
上面的代码只运行并修改了<> .exe.config而不是项目中的app.config。
我真的不确定哪个是正确的,或者我遗漏了任何东西。
我在VS 2012,c#4.5,它是控制台应用程序。 截至目前,我的控制台中没有其他代码,app.config是
这只是对app.config的错误理解。 您希望应用程序修改您的源代码是不正确的。
当您运行程序时,它会创建app.config
的副本到bin / debug或bin / release文件夹。
你的第二个解决方案很好。 应用程序按预期工作。
Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); config.AppSettings.Settings["PresentationFolder"].Value = path; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings");
其中:path – 是“new value”,“appSettings” – 是App.config中的Section