2015-10-15 59 views
0

使用下面的代码来更新app.config的一些值(我在app.config文件中有配置文件路径)。当部署其获取错误时,我认为它的becouse app.config文件改为exe。如何改变我的代码工作的调试时间以及部署时间在C#中部署后访问App.Config文件

var appPath = ConfigurationManager.AppSettings["configPath"].ToString(); 
      string configFile = System.IO.Path.Combine(appPath, "App.config"); 
      var configFileMap = new ExeConfigurationFileMap(); 
      configFileMap.ExeConfigFilename = configFile; 
      System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); 

config.AppSettings.Settings["InvoiceInterval"].Value = InvoiceIntervalVal.ToString(); 
+0

为什么你要改变那个配置文件在运行时? –

回答

0
After compilation App.Config will be available as 
YourConsoleApplication.exe.Config inside application bin. 
You can do like: 
var beforeInvoiceInterval = ConfigurationManager.AppSettings 
["InvoiceInterval"].ToString(); 
     ConfigurationManager.AppSettings["InvoiceInterval"] = "Your value"; 
var afterInvoiceInterval = ConfigurationManager.AppSettings 
["InvoiceInterval"].ToString(); 

afterInvoiceInterval will contain the value you assigned but it'll not 
modify YourConsoleApplication.exe.Config. 
+0

是的,这是正确的。我是一个java的家伙,所以我虽然它会直接影响到App.config文件我mistak感谢您的帮助:) –

1

感谢喜逢体例如答复。我解决了自己的问题,这只是一个混乱。我是一个java家伙,我新创建.net .net App.config文件,在Debug文件夹文件中编译并创建.config,即使调试它访问Debug文件夹中的.config文件。所以实际上,如果以编程方式更改App.config中的值,它不会更改App.config文件。它会更改debug文件中的.config文件,如调试文件夹中的[project name] .vshost.exe.config。

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings["InvoiceInterval"].Value = InvoiceIntervalVal.ToString(); 
       config.AppSettings.Settings["directPaymentInterval"].Value = directPaymentIntervalVal.ToString(); 
       config.AppSettings.Settings["paymentStatusInterval"].Value = paymentStatusIntervalVal.ToString(); 
       config.Save(); 
       ConfigurationManager.RefreshSection("appSettings"); 

使用上面的代码,您可以在调试时也可以在运行时更改App.config文件的值。但这些更改似乎不在App.config文件中。但你可以看到它所属的exe文件的变化。在我的情况下,它是在src \ Vetserve.Credicare \ bin \ Debug \ Vetserve.Credicare.vshost.exe.config