在安装项目中可以执行自定义操作,包括制定一个exe dll vbs js等类型的文件。之前我们是利用一个exe,但感觉使用起来限制很多,如不方便定制,一次只执行一个exe,不方便传参数等。在.net中可以写出一个安装类来,通过override出Commit、install 、Uninstall等函数实现自定义操作。这里是一个实际的示例:
namespace InstHelper
{
[RunInstaller(true)]
public partial class InstHelper : Installer
{
public InstHelper()
{
InitializeComponent();
}
public override void Commit(System.Collections.IDictionary savedState)
{
base.Commit(savedState);
string exepath;
//注册服务
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
StringBuilder sb = new StringBuilder();
sb.AppendFormat(" create DaykeyPcManager binpath= \"{0}\\PcManagerSvc.exe\"", path);
System.Diagnostics.Process.Start("sc.exe", sb.ToString());
//配置服务
sb.Length = 0;
sb.Append("config DaykeyPcManager type= interact type= own");
System.Diagnostics.Process.Start("sc.exe", sb.ToString());
//添加防火墙列外
sb.Length = 0;
sb.AppendFormat(" firewall add allowedprogram \"{0}\\PcManagerSvc.exe\" ABCD ENABLE", path);
System.Diagnostics.Process.Start("netsh.exe", sb.ToString());
//启动服务
exepath = path + "\\start.bat";
System.Diagnostics.Process.Start(exepath);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
//停止服务
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string exepath = path + "\\stop.bat";
System.Diagnostics.Process.Start(exepath);
//删除防火墙列外
StringBuilder sb = new StringBuilder();
sb.Length = 0;
sb.AppendFormat(" firewall delete allowedprogram \"{0}\\PcManagerSvc.exe\"", path);
System.Diagnostics.Process.Start("netsh.exe", sb.ToString());
//删除服务
sb.Length = 0;
sb.Append("delete DaykeyPcManager");
System.Diagnostics.Process.Start("sc.exe", sb.ToString());
}
protected override void OnBeforeUninstall(System.Collections.IDictionary savedState)
{
base.OnBeforeUninstall(savedState);
//停止服务
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string exepath = path + "\\stop.bat";
System.Diagnostics.Process.Start(exepath);
}
//public override void Install(System.Collections.IDictionary stateSaver)
//{
// base.Install(stateSaver);
// System.Diagnostics.Process.Start("http://www.youkuaiyun.com");
//}
}
}