10.代碼如下(請注意看代碼注釋):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Configuration;
using System.XML;
using System.IO;
namespace SetSetup
{
/// <summary>
/// 繼承安裝類
/// www.szitr.com
/// </summary>
[RunInstaller(true)]
public partial class SetSqlConStr : Installer
{
public SetSqlConStr()
{
InitializeComponent();
}
/// <summary>
/// 重寫基類的安裝方法
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
//得到用戶輸入的參數
//參數來自於後面 第 14 步 自定義操作的參數
//自定義操作參數的屬性CustoMactionData:/SqlServerIP= [SQLSERVER_NAME] /DataBase=[DATABASE_NAME] /UserName=[USERNAME] /Password=[PASSWord] /TargetDir="[TARGETDIR]\"
//中括號中的就是之前各文本框的Edit_Property值.最後一個TARGETDIR是 安裝路徑,注意後面還有個反斜桿
string sqlServerIP = this.Context.Parameters ["SqlServerIP"];
string database = this.Context.Parameters["DataBase"];
string userName = this.Context.Parameters["UserName"];
string password = this.Context.Parameters["PassWord"];
string targetdir = this.Context.Parameters["TargetDir"];
//這裡寫你要執行的代碼
//組合連接字符串
string conString = String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};Persist Security Info=True", sqlServerIP, database, userName, passWord);
//更新連接字串設定值,WinUI.exe.config 要改成你設定檔的名稱
UpdateConConfig("ConnectionString", conString, targetdir + "WinUI.exe.config");
}
/// <summary>
/// 修改設定檔連接字符串的值
/// </summary>
/// <param name="conName">連接字符串名稱</param>
/// <param name="conString">連接字符串</param>
/// <param name="configfilePath">設定檔路徑及名稱 </param>
public static void UpdateConConfig(string conName, string conString,string configfilePath)
{
XmlDocument xmlDoc = new XMLDocument();
//讀取設定檔
XMLDoc.Load(configfilePath);
//取得連接字符串的節點
XmlNode xmlNode = XMLDoc.SelectSingleNode ("configuration/connectionStrings/add[@name='" + conName + "']");
//修改連接字符串
XMLNode.Attributes["connectionString"].InnerText = conString;
//保存
XMLDoc.Save(configfilePath);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
}
public override void Commit(System.Collections.IDictionary savedState)
{
base.Commit(savedState);
}
public override void Rollback(System.Collections.IDictionary savedState)
{
base.Rollback(savedState);
}
}
}