一.C#运用ProcessStartInfo安装服务,卸载服务,启用服务,关闭服务的操作!
- C#运用ProcessStartInfo安装服务,卸载服务,启用服务,关闭服务的操作!
- /// <summary>
- /// 从CMD运行里面启用服务
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void Button4_Click1(object sender, EventArgs e)
- {
- //开启服务
- ProcessStartInfo a = new ProcessStartInfo(@"c:/windows/system32/cmd.exe","/c net start 服务名");
- a.WindowStyle = ProcessWindowStyle.Hidden;
- Process process = Process.Start(a);
- }
- protected void Button5_Click1(object sender, EventArgs e)
- {
- //关闭服务
- ProcessStartInfo a = new ProcessStartInfo(@"c:/windows/system32/cmd.exe","/c net stop 服务名");
- a.WindowStyle = ProcessWindowStyle.Hidden;
- Process process = Process.Start(a);
- }
- protected void Button6_Click1(object sender, EventArgs e)
- {
- ProcessStartInfo a = new ProcessStartInfo(@"D://zhengxinle//xiangmu//NetView//NetView//Transmit.exe" ,"-install");
- Console.Write("安装服务成功");
- a.WindowStyle = ProcessWindowStyle.Hidden;
- Process process = Process.Start(a);
- }
- protected void Button7_Click1(object sender, EventArgs e)
- {
- ProcessStartInfo a = new ProcessStartInfo(@"D://zhengxinle//xiangmu//NetView//NetView//Transmit.exe" ,"-remove");
- Console.Write("卸载服务成功");
- a.WindowStyle = ProcessWindowStyle.Hidden;
- Process process = Process.Start(a);
- }
二.通过API函数加载
- using System.Configuration.Install;
- using System.ServiceProcess;
- using System.Runtime.InteropServices;
- #region DLLImport
- [DllImport("advapi32.dll")]
- public static extern IntPtr OpenSCManager(string lpMachineName,string lpSCDB, int scParameter);
- [DllImport("Advapi32.dll")]
- public static extern IntPtr CreateService(IntPtr SC_HANDLE,string lpSvcName,string lpDisplayName,
- int dwDesiredAccess,int dwServiceType, int dwStartType,int dwErrorControl,string lpPathName,
- string lpLoadOrderGroup,int lpdwTagId, string lpDependencies,string lpServiceStartName,string lpPassword);
- [DllImport("advapi32.dll")]
- public static extern void CloseServiceHandle(IntPtr SCHANDLE);
- [DllImport("advapi32.dll")]
- public static extern int StartService(IntPtr SVHANDLE,int dwNumServiceArgs,string lpServiceArgVectors);
- [DllImport("advapi32.dll",SetLastError=true)]
- public static extern IntPtr OpenService(IntPtr SCHANDLE,string lpSvcName,int dwNumServiceArgs);
- [DllImport("advapi32.dll")]
- public static extern int DeleteService(IntPtr SVHANDLE);
- [DllImport("kernel32.dll")]
- public static extern int GetLastError();
- #endregion DLLImport
- ///
- /// 安装和运行
- /// /// C#安装程序路径.
- /// /// 服务名
- /// /// 服务显示名称.
- /// /// 服务安装是否成功.
- public bool InstallService(string svcPath, string svcName, string svcDispName)
- {
- #region Constants declaration.
- int SC_MANAGER_CREATE_SERVICE = 0x0002;
- int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
- //int SERVICE_DEMAND_START = 0x00000003;
- int SERVICE_ERROR_NORMAL = 0x00000001;
- int STANDARD_RIGHTS_REQUIRED = 0xF0000;
- int SERVICE_QUERY_CONFIG = 0x0001;
- int SERVICE_CHANGE_CONFIG = 0x0002;
- int SERVICE_QUERY_STATUS = 0x0004;
- int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;
- int SERVICE_START =0x0010;
- int SERVICE_STOP =0x0020;
- int SERVICE_PAUSE_CONTINUE =0x0040;
- int SERVICE_INTERROGATE =0x0080;
- int SERVICE_USER_DEFINED_CONTROL =0x0100;
- int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
- SERVICE_QUERY_CONFIG |
- SERVICE_CHANGE_CONFIG |
- SERVICE_QUERY_STATUS |
- SERVICE_ENUMERATE_DEPENDENTS |
- SERVICE_START |
- SERVICE_STOP |
- SERVICE_PAUSE_CONTINUE |
- SERVICE_INTERROGATE |
- SERVICE_USER_DEFINED_CONTROL);
- int SERVICE_AUTO_START = 0x00000002;
- #endregion Constants declaration.
- try {
- IntPtr sc_handle = OpenSCManager(null,null,SC_MANAGER_CREATE_SERVICE);
- if (sc_handle.ToInt32() != 0)
- {
- IntPtr sv_handle = CreateService(sc_handle,svcName,svcDispName,SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,svcPath,null,0,null,null,null);
- if(sv_handle.ToInt32() ==0)
- {
- CloseServiceHandle(sc_handle);
- return false;
- }
- else
- {
- //试尝启动服务
- int i = StartService(sv_handle,0,null);
- if(i==0)
- {
- return false;
- }
- CloseServiceHandle(sc_handle);
- return true;
- }
- }
- else
- return false;
- }
- catch(Exception e)
- {
- throw e;
- }
- }
- ///
- /// 反安装服务.
- /// ///
- /// 服务名.
- public bool UnInstallService(string svcName)
- {
- int GENERIC_WRITE = 0x40000000;
- IntPtr sc_hndl = OpenSCManager(null,null,GENERIC_WRITE);
- if(sc_hndl.ToInt32() !=0)
- { int DELETE = 0x10000;
- IntPtr svc_hndl = OpenService(sc_hndl,svcName,DELETE);
- if(svc_hndl.ToInt32() !=0)
- {
- int i = DeleteService(svc_hndl);
- if (i != 0)
- {
- CloseServiceHandle(sc_hndl);
- return true;
- }
- else
- {
- CloseServiceHandle(sc_hndl);
- return false;
- }
- }
- else
- return false;
- }
- else
- return false;
- }
三.加载一个程序集,并运行其中的所有安装程序。
- @@@是服务的名字
- /// <summary>
- /// 用ServiceController启用服务
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void Button5_Click(object sender, EventArgs e)
- {
- System.ServiceProcess.ServiceController myController =
- new System.ServiceProcess.ServiceController("@@@");
- ///ContinuePending 服务即将继续。这对应于 Win32 SERVICE_CONTINUE_PENDING 常数,该常数定义为 0x00000005。
- //Paused 服务已暂停。这对应于 Win32 SERVICE_PAUSED 常数,该常数定义为 0x00000007。
- //PausePending 服务即将暂停。这对应于 Win32 SERVICE_PAUSE_PENDING 常数,该常数定义为 0x00000006。
- //Running 服务正在运行。这对应于 Win32 SERVICE_RUNNING 常数,该常数定义为 0x00000004。
- //StartPending 服务正在启动。这对应于 Win32 SERVICE_START_PENDING 常数,该常数定义为 0x00000002。
- //Stopped 服务未运行。这对应于 Win32 SERVICE_STOPPED 常数,该常数定义为 0x00000001。
- //StopPending 服务正在停止。这对应于 Win32 SERVICE_STOP_PENDING 常数,该常数定义为 0x00000003。
- if (myController.Status.Equals(ServiceControllerStatus.Stopped)||myController.Status.Equals(ServiceControllerStatus.StopPending))
- {
- myController.Start();
- this.Button5.Text="关闭服务";
- Response.Write("<mce:script language=javascript><!--
- alert('开启');
- // --></mce:script>");
- }
- else
- {
- myController.Stop();
- this.Button5.Text="开启服务";
- Response.Write("<mce:script language=javascript><!--
- alert('关闭服务');
- // --></mce:script>");
- }
- }
- 一、安装服务:
- private void InstallService(IDictionary stateSaver, string filepath)
- {
- try
- {
- System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("ServiceName");
- if(!ServiceIsExisted("ServiceName"))
- {
- //Install Service
- AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
- myAssemblyInstaller.UseNewContext = true;
- myAssemblyInstaller.Path =filepath;
- myAssemblyInstaller.Install(stateSaver);
- myAssemblyInstaller.Commit(stateSaver);
- myAssemblyInstaller.Dispose();
- //--Start Service
- service.Start();
- }
- else
- {
- if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
- {
- service.Start();
- }
- }
- }
- catch (Exception ex)
- {
- throw new Exception("installServiceError/n" + ex.Message);
- }
- }
- 二、卸载windows服务:
- private void UnInstallService(string filepath)
- {
- try
- {
- if (ServiceIsExisted("ServiceName"))
- {
- //UnInstall Service
- AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
- myAssemblyInstaller.UseNewContext = true;
- myAssemblyInstaller.Path = filepath;
- myAssemblyInstaller.Uninstall(null);
- myAssemblyInstaller.Dispose();
- }
- }
- catch (Exception ex)
- {
- throw new Exception("unInstallServiceError/n" + ex.Message);
- }
- }
- 三、判断window服务是否存在:
- private bool ServiceIsExisted(string serviceName)
- {
- ServiceController[] services = ServiceController.GetServices();
- foreach (ServiceController s in services)
- {
- if (s.ServiceName == serviceName)
- {
- return true;
- }
- }
- return false;
- }
- 四、启动服务:
- private void StartService(string serviceName)
- {
- if (ServiceIsExisted(serviceName))
- {
- System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
- if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
- {
- service.Start();
- for (int i = 0; i < 60; i++)
- {
- service.Refresh();
- System.Threading.Thread.Sleep(1000);
- if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
- {
- break;
- }
- if (i == 59)
- {
- throw new Exception(startServiceError.Replace("$s$", serviceName));
- }
- }
- }
- }
- }
- 五、停止服务:
- private void StopService(string serviceName)
- {
- if (ServiceIsExisted(serviceName))
- {
- System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
- if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
- {
- service.Stop();
- for (int i = 0; i < 60; i++)
- {
- service.Refresh();
- System.Threading.Thread.Sleep(1000);
- if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
- {
- break;
- }
- if (i == 59)
- {
- throw new Exception(stopServiceError.Replace("$s$", serviceName));
- }
- }
- }
- }
- }
- 注:手动安装window服务的方法:
- 在“Visual Studio 2005 命令提示”窗口中,运行:
- 安装服务:installutil servicepath
- 卸除服务:installutil /u servicepath