自動設定軟體
主軟體已經在電腦上運行,我現在要啟動相關的小工具,有要配置相同的軟體參數,如資料庫連接配置,體麻煩就想讓小工具自動讀取主軟體上的配置資訊到小工具上。
需求:
變化點:
1:主軟體沒有運行,小工具照樣可以運行,那就需要小工具可以手動設定
步驟:
1:讀取進程
2:擷取進程位置
3:找到需要的設定檔
4:讀取設定檔資訊到小工具上
5:小工具儲存配置資訊
實現:
主軟體進程資訊:
尋找設定檔:
<?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>
介面操作:
讀取源碼:
//讀取進程擷取配置 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("讀取失敗!請手動輸入配置資訊。"); } }