问题
Basically I have two projects. Lets name it Project A and Project B.
Both projects are WinForm apps.
There are times that I will call forms in Project B from Project A. Since both projects has different implementation of connection strings, business layer, services, and models, these are all set under app.config per project, which have different content, of course.
In other words, Project A has its own app.config. Project B has its own app.config.
Now I want to use or rather switch app.config at runtime on my winform/winapp project. Is this possible?
The problem is that when I launched the whole solution (Project A is set as startup), the app.config of Project A is loaded. Now I want to use the app.config of Project B everytime I will call Project B winforms.
Thanks for any inputs you can provide!
回答1:
If you want to change your config file at run time, this code works perfectly for me, first create a class which you will call to change your config file:
public abstract class AppConfig : IDisposable
{
public static AppConfig Change(string path)
{
return new ChangeAppConfig(path);
}
public abstract void Dispose();
private class ChangeAppConfig : AppConfig
{
private readonly string oldConfig =
AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
private bool disposedValue;
public ChangeAppConfig(string path)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
ResetConfigMechanism();
}
public override void Dispose()
{
if (!disposedValue)
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig);
ResetConfigMechanism();
disposedValue = true;
}
GC.SuppressFinalize(this);
}
private static void ResetConfigMechanism()
{
typeof(ConfigurationManager)
.GetField("s_initState", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, 0);
typeof(ConfigurationManager)
.GetField("s_configSystem", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
typeof(ConfigurationManager)
.Assembly.GetTypes()
.Where(x => x.FullName ==
"System.Configuration.ClientConfigPaths")
.First()
.GetField("s_current", BindingFlags.NonPublic |
BindingFlags.Static)
.SetValue(null, null);
}
}
}
Then to call the this on your program, you can do this:
using (AppConfig.Change(@"D:\app.config"))
{
//TODO:
}
回答2:
Your question has been previously asked:
Use the 'Add Existing Item' menu from Visual Studio's Solution Explorer, to add a link to the app.config in the first project. The details are given in this link:
How to Share App.config?
来源:https://stackoverflow.com/questions/41978642/is-it-possible-to-use-different-config-file-on-different-winform-projects-at-run