简体   繁体   中英

How to update app.config in c#

My project is developing in WPF with MVVM. In viewModel consuming WCF services. In View app.config file is present and it contains information about WCF configurations like endpoint info... . We have two services like service1 and service2 both are identical having function but the service address will be different. Service1 is communicating with DataBase1 and the service2 is communicating with Database2, so service to DB is one to one mapping. In view a ComboBox is there which will show two option like DB1 and DB2. Based the comboBox selection i have to update my app.config file [endpoint address] as per WPF-MVVM pattern. Because application should re-init with new service - DB function call. So, If ComboBox selection changed where command will invoke which is (command) is written in ViewModel. So how to update config file?

Else is there anyother way to achieve this?

配置必须在您的启动项目中,这可能是问题所在

You have two identical WCF services, and you want the user to use a ComboBox to choose which one your application interacts with. So your application only needs a single definition for the proxy in the config file. It does not matter which of the two URLs this is pointing at.

You can programmatically set the URL of the endpoint at runtime in the constructor of the proxy. I can't tell from the question what protocol you're using but there are some examples here of how to do this.

You need to keep a list of what the possible URL values are, to allow the user to make a choice (but this is different from which one has been selected, I'll get to that later). I'd suggest having the alternative URLs in config, in this part of the file (I'm going to guess at the http protocol, just so you can see what I mean)...

<configuration>
    ...
    <appSettings>
         <add key="Endpoint1" value="http://whatever"/>
         <add key="Endpoint2" value="http://whatever"/>
    </appSettings>
    ...
</configuration>

Then on startup, iterate through these to put them in your ComboBox:

var appSettings = ConfigurationManager.AppSettings;
foreach (var key in appSettings.AllKeys.Where(x=>x.StartsWith("Endpoint"))
{
    // put appSettings[key] into the combobox (in a list in your viewmodel if you use MVVM)
}

Then you need to store which one of these have been selected by this user (and remember to pre-select that value on startup). I'd suggest using the "user settings", which (unlike the "App.config" file) allows the values to be changed. See User Settings in C# for how to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM