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

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

基本上我有两个项目。我们将其命名为项目 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。

感谢您提供的任何意见!

最佳答案

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

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:
        }

关于c# - 是否可以在运行时在不同的 Winform 项目上使用不同的配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978642/

相关文章:

C# List<Object>.Equals 对象比较失败

c# - 用于一些 flash 的简单动画库

c# - 空合并运算符是否有 "opposite"? (……用任何语言?)

c# - 如何在 MVC 5 的数据库中创建新表?

c# - 自定义操作 session.message 不显示消息框

c# - 将 C# 库移植到 Windows Phone 8?

c# - MVP Winform 解决方案/项目文件布局

c# - Entity Framework : Server did not respond within the specified time out interval

c# - Jquery AJAX 与 ASP.NET WebMethod 刷新整个页面

c# - 需要有关字符串数组中简单字符串排序方法的帮助