app.config修改值c#
这个问题在这里得到解决
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:AppScheduleScheduleApp.config"; 这会修改项目中的app.config以及<<在bin / debug中的appname>> .exe.config.但我不认为这是一个可行的解决方案,因为应用程序可以部署在任何路径上.所以对configPath进行硬编码是行不通的. 然后我再次修改了给定的configFile string configFile = System.IO.Path.Combine(appPath,"<appname>.exe.config"); 上面的代码仅运行并修改<< appname>> .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> 解决方法
这只是对app.config的错误理解.
您希望应用程序修改您的源代码是不正确的. 运行程序时,它会创建app.config的副本到bin / debug或bin / release文件夹. 你的第二个解决方案很好.应用程序按预期工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |