The VisualStudio configuration file is very good and powerful, it is very convenient to save the database connection string or the key value pair, only need to pass through the ConfigurationManager connectionstrings or the AppSettings property to be able to use at any time. But ConfigurationManager opens the project's default profile, and I sometimes have this requirement: engineering A has some way of referencing the project B,a and B have their own configuration, I do not want to write the configuration of B to a configuration file, but I hope B also has its own configuration file. The runtime program starts from a, so how can I get ConfigurationManager to access the configuration file of B correctly?
Turning over ConfigurationManager's signature, there is a way to attract my attention: openexeconfiguration (String exepath). It seems that I can pass the configuration file path of Project B as a parameter to this method, and then return a configuration object after execution, and then I can get a smooth access to the config information.
Unfortunately the reality is cruel, openexeconfiguration is really a strange way, I found that successful calls need to meet a few shocking conditions:
1, the parameter exepath must be *.exe or *.config format (there may be other formats, but *.dll certainly not)
2, exepath corresponding file must exist (for example, ExePath = "C:/projectb.exe", the C disk must have a file called ProjectB.exe), but in fact, this file is not used at all.
3, the method call after the final open configuration file is actually named ExePath + ". config" (So exepath = "C:/projectb.exe" When the configuration file is C:/projectb.exe.config, and *.config configuration file You have to call *.config.config)
It may be that Microsoft engineers have another plan, or this method may not be used in my imagination, in short, the above conditions really let me down. If you must add a blank text to the directory each time, take the name suffix to the. exe, and then change the actual configuration file suffix to. exe.config. This openexeconfiguration will not make me more convenient, will only make me more tangled.
ConfigurationManager has a few similar methods, but I don't know how to use them, so I've searched Google and MSDN. Finally found a way to really solve my problem: openmappedexeconfiguration
Not much to say, directly on the code:
String Configpath = ...;
Execonfigurationfilemap map = new Execonfigurationfilemap ();
Map. Execonfigfilename = Configpath;
Config = configurationmanager.openmappedexeconfiguration (map, Configurationuserlevel.none);
Let ConfigurationManager open any configuration file