是否可以在运行时在不同的 Winform 项目上使用不同的配置文件?

Is it possible to use different config file on different Winform Projects at runtime?

基本上我有两个项目。让我们将其命名为项目 A 和项目 B。

这两个项目都是 WinForm 应用程序。

有时我会从项目 A 调用项目 B 中的表单。由于两个项目的连接字符串、业务层、服务和模型的实现不同,因此这些都在每个项目下设置 app.config ,当然有不同的内容。

也就是说,项目A有自己的app.config。项目 B 有自己的 app.config.

现在我想在 winform/winapp 项目的运行时使用或切换 app.config。这可能吗?

问题是当我启动整个解决方案时(项目 A 设置为启动),项目 A 的 app.config 被加载。现在我想每次调用项目 B winforms 时都使用项目 B 的 app.config。

感谢您提供的任何意见!

您的问题之前有人问过:

使用 Visual Studio 解决方案资源管理器中的 'Add Existing Item' 菜单,将 link 添加到第一个项目中的 app.config。详情在此link:

How to Share App.config?

如果您想在 运行 时更改您的配置文件,此代码对我来说非常适合,首先创建一个 class ,您将调用它来更改您的配置文件:

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);
        }
    }
}

然后要在您的程序中调用 this,您可以这样做:

 using (AppConfig.Change(@"D:\app.config"))
        {
           //TODO:
        }