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

时间:2017-02-01 11:27:19

标签: c# .net winforms visual-studio app-config

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

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

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

换句话说,Project A有自己的app.config。项目B有自己的app.config。

现在我想在winform / winapp项目中使用或者更确切地说在运行时切换app.config。这可能吗?

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

感谢您提供的任何输入!

2 个答案:

答案 0 :(得分:1)

如果你想在运行时更改你的配置文件,这段代码对我来说非常合适,首先创建一个你打电话来更改配置文件的类:

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

然后在你的程序中调用它,你可以这样做:

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

答案 1 :(得分:-1)

之前已经问过你的问题:

使用'添加现有项目' Visual Studio的解决方案资源管理器中的菜单,用于在第一个项目中添加指向app.config的链接。详情请见以下链接:

How to Share App.config?

相关问题