您的位置:首页 > 编程语言

使用程序代码安装/卸载.net服务(不使用InstallUtil.exe)

2011-11-29 12:36 776 查看
在上一篇文章(C#系统服务定时执行)中讲到使用InstallUtil.exe来安装和卸载系统服务。那么,我们是否可以使用自己写的代码来做这些工作呢?答案是肯定的。

下面我们来看看如何实现:

1、首先我们照上一片文章配置好系统服务,并且生成一个exe文件。

2、这里我们用一个winform来做,上面画2个按钮(一个安装服务,一个卸载服务)。

3、安装服务按钮点击事件

/// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
string[] args = { "HP.Travel_Mail_Service.exe" };//要安装的服务文件(就是用 InstallUtil.exe 工具安装时的参数)
ServiceController svcCtrl = new ServiceController(serviceName);
if (!ServiceIsExisted(serviceName))
{
try
{
System.Configuration.Install.ManagedInstallerClass.InstallHelper(args);
MessageBox.Show("服务安装成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
else
{
MessageBox.Show("该服务已经存在,不用重复安装。");
}
}


4、卸载服务点击事件

/// <summary>
/// 卸载指定服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
if (ServiceIsExisted(serviceName))
{
//UnInstall Service
System.Configuration.Install.AssemblyInstaller myAssemblyInstaller = new System.Configuration.Install.AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = "HP.Travel_Mail_Service.exe";
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
MessageBox.Show("卸载服务成功!");
}
else
{
MessageBox.Show("服务不存在!");
}

}
catch (Exception)
{
MessageBox.Show("卸载服务失败!");
}

}
}


5、检测服务是否存在代码

/// <summary>
/// 检查指定的服务是否存在
/// </summary>
/// <param name="serviceName">要查找的服务名字</param>
/// <returns></returns>
private bool ServiceIsExisted(string svcName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName == svcName)
{
return true;
}
}
return false;
}


然后把前面生成的服务exe和这个winform生成的可执行文件放到同一个目录下,

运行winform点按钮就可实现和运行 InstallUtil.exe 工具一样的效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐