1 服务程序的开始与停止.
public Service1()
{
InitializeComponent();
StartAppPath = Assembly.GetExecutingAssembly().GetName().CodeBase;//安装路径
StartAppPath = StartAppPath.Substring(8, StartAppPath.LastIndexOf(@"/") - 8) + @"/DMService.exe";//服务程序要执行的EXE
proc.StartInfo.FileName = StartAppPath;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
}
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
try
{
bool a = proc.Start();
}
catch (System.Exception ex)
{
//错误处理
}
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
try
{
proc.Kill(); ;
}
catch (System.Exception ex)
{
//错误处理
}
}
2 然后在Service1的设计器中右击“添加安装程序”在ProjectInstaller中的InitializeComponent()内添加
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
3 服务程序的安装与卸载 下面的代码要添加在服务程序要执行的EXE程序中``在这个EXE项目中添加-新建项-安装程序类
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);//C://WINDOWS//Microsoft.NET//Framework//v2.0.50727//
string path = Assembly.GetExecutingAssembly().GetName().CodeBase; //获取安装路径
path = path.Substring(0, path.LastIndexOf(@"/"));
// 下面挂到windows服务中
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.StandardInput.WriteLine("cd C://WINDOWS//Microsoft.NET//Framework//v2.0.50727//");//installutil.exe的路径
p.StandardInput.WriteLine("installutil /"" + path + "//DMSer.exe/""); //这个EXE就是上面的服务程序
p.StandardInput.WriteLine("net start DM");
p.StandardInput.WriteLine("exit");
p.WaitForExit();
p.Close();
}
protected override void OnBeforeUninstall(IDictionary savedState)
{
base.OnBeforeUninstall(savedState);
string path = Assembly.GetExecutingAssembly().GetName().CodeBase;
path = path.Substring(0, path.LastIndexOf(@"/"));
// 下面从windows服务中移除
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";// cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.StandardInput.WriteLine("cd C://WINDOWS//Microsoft.NET//Framework//v2.0.50727//");//installutil.exe的路径
p.StandardInput.WriteLine("net stop DM");
p.StandardInput.WriteLine("installutil /u /"" + path + "//DMSer.exe/"");
p.StandardInput.WriteLine("exit");
p.WaitForExit();
p.Close();
}
}