C# WinForm 技巧七:读取进程获取进程信息

自动配置软件

主软件已经在电脑上运行,我现在要启动相关的小工具,有要配置相同的软件参数,如数据库连接配置,体麻烦就想让小工具自动读取主软件上的配置信息到小工具上。

需求:

变化点:

     1:主软件没有运行,小工具照样可以运行,那就需要小工具可以手动配置

 步骤:

     1:读取进程

      2:获取进程位置

      3:找到需要的配置文件

      4:读取配置文件信息到小工具上

      5:小工具保存配置信息

实现:

主软件进程信息:

image

寻找配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!-- 连接字符串 -->
    <add key="server"  value="LUOMG-PC"/>
    <add key="uid" value="sa"/>
    <add key="pwd" value="123456"/>
    <add key="db" value="HeatingFs"/>
  </appSettings>
</configuration>

界面操作:

image

读取源码:

//读取进程获取配置
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                #region 读取进程获取配置
                Process[] myProcess = Process.GetProcessesByName("HaiLin");
                foreach (Process ps in myProcess)
                {
                    string fileName = ps.MainModule.FileName;
                    string configFile = Path.GetDirectoryName(fileName) + @"\HaiLin.exe";
                    if (File.Exists(configFile))
                    {
                        Configuration _innerConfig = ConfigurationManager.OpenExeConfiguration(configFile);
                        if (_innerConfig.AppSettings.Settings.Count > 0)
                        {
                            txt_server.Text = _innerConfig.AppSettings.Settings["server"].Value;
                            txt_database.Text = _innerConfig.AppSettings.Settings["db"].Value;
                            txt_sa.Text = _innerConfig.AppSettings.Settings["uid"].Value;
                            txt_pwd.Text = _innerConfig.AppSettings.Settings["pwd"].Value;
                            MessageBox.Show("读取成功!请点击设置保存。");
                        }
                    }
                    else
                    {
                        MessageBox.Show("配置文件不存在!" + configFile);
                    }
                }
                #endregion
            }
            catch
            {
                MessageBox.Show("读取失败!请手动输入配置信息。");
            }
        }
原文地址:https://www.cnblogs.com/luomingui/p/2888582.html