多个工程共享一个配置文件


启动程序:

ProcessStartInfo startInfo = new ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + "JC.Interaction.BonusControl.exe");
                //startInfo.Arguments = XMLHelper.JsonSerializer(new StartParam { CodeStart = true, Id = (sender as Button).Tag.ToString(), ConfigName = Process.GetCurrentProcess().MainModule.ModuleName });
                startInfo.Arguments = string.Format("{0}|{1}|{2}", true, (sender as Button).Tag.ToString(), Process.GetCurrentProcess().MainModule.ModuleName);
                Process = Process.Start(startInfo);
                Process.EnableRaisingEvents = true;
                Process.SynchronizingObject = this;
                Process.Exited += (ss, ee) =>
                {
                    this.Visible = true;
                };

上面这段代码意思是

启动 AppDomain.CurrentDomain.BaseDirectory 目录下的JC.Interaction.BonusControl.exe 程序

设置调用目标程序的参数

Process.EnableRaisingEvents 设置调用目标进程被关闭时是否触发 Exited 事件

Process.SynchronizingObject 设置执行 Exited 事件的执行者为启动它的程序。不然会报错,因为跨线程了。

这里主要说一下 Arguments 的参数  ,这里所有的参数都是自己定义的,你想用什么参数就传什么参数,所以我就是这里把配置文件传过去的。

说到配置文件 那么就得说 winform 的默认配置文件 App.config 。

它在编译后会生成为 当前项目名称+".config" 例如:项目名称为 JC.System.Bonus 。那么 App.config 就会被生成为JC.System.Bonus.config

获取启动程序名称: Process.GetCurrentProcess().MainModule.ModuleName

所以我们这里就把这个参数传过去了。 

---------------- 题外话---------------

本想用序列化对象传参数的  不知道为什么  在另一个程序里面一直都获取不到,到处查资料,弄了几个小时放弃了,直接用分隔符。  我不知道是参数里面有什么特殊字符,还是字数有限制什么的  。


目标程序:

 [STAThread]
        public static void Main(string[] args)
        {
            try
            {
                //防止用户直接启动程序
                var _params = args[0].Split('|');
                if (Convert.ToBoolean(_params[0]))
                {
                    CommonManager.Id = _params[1];
                    //设置此工程的配置文件
                    System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, _params[2] + ".config"));
                    new Application().Run(new MainWindow());
                }
                else {
                    Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Environment.Exit(0);
            }
        }
上面就是目标程序的入口

刚才我们传过来的参数就在 args 里面    这里我用的分隔符来传参的。

然后我们用 

 System.AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE",配置文件名称);  来设置当前程序的默认 config 
  System.AppDomain.CurrentDomain.BaseDirectory 是获取的项目路径,就是编译生成之后的debug路径。

 _params[2] + ".config" 这个参数就是刚才传过来的,后面再加上config后缀就可以了。


最后我们用  System.Configuration.ConfigurationManager.AppSettings["key"]   就可以获取到config里面的键值对信息了。





AppDomain.CurrentDomain.BaseDirectory 目录下的 JC.Interaction.BonusControl.exe 程序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值