C# windows 服务 操作实例

先说明一下windows服务开发前要明白的东西,DOS


程序所在物理路径
D:workObjectxx.exe

输入CMD
cd C:WINDOWSMicrosoft.NETFrameworkv2.0.50727
cd C:WINDOWSMicrosoft.NETFrameworkv4.0.30319

安装服务
installUtil D:workObjectxx.exe

卸载服务
installUtil /u D:workObjectxx.exe

查看Window服务
services.msc


C:>
使用命令行启动服务
在cmd下可有两种方法打开,net和sc,net用于打开没有被禁用的服务,语法是:
net start 服务名                启动 net start 服务名
net stop 服务名                 停止 net stop 服务名

用sc可打开被禁用的服务,语法是:
sc config 服务名 start= demand     //手动
sc condig 服务名 start= auto       //自动
sc config 服务名 start= disabled   //禁用
sc start  服务名
sc stop   服务名

下面是实例代码 

 /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            // 同一进程中可以运行多个用户服务。若要将
            // 另一个服务添加到此进程中,请更改下行以
            // 创建另一个服务对象。例如,
            //
            //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
            //
            if (args.Length == 0)
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] { new RemoveCacheService() }; ///new ServiceBase[] { new Service1() }; 实现逻辑入口
                ServiceBase.Run(ServicesToRun);
            }
            // 安装服务
            else if (args[0].ToLower() == "/i" || args[0].ToLower() == "-i")
            {
                try
                {
                    string[] cmdline = { };
                    string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location;

                    TransactedInstaller transactedInstaller = new TransactedInstaller();
                    AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline);
                    transactedInstaller.Installers.Add(assemblyInstaller);
                    transactedInstaller.Install(new System.Collections.Hashtable());
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                }
            }
            // 删除服务
            else if (args[0].ToLower() == "/u" || args[0].ToLower() == "-u")
            {
                try
                {
                    string[] cmdline = { };
                    string serviceFileName = System.Reflection.Assembly.GetExecutingAssembly().Location;

                    TransactedInstaller transactedInstaller = new TransactedInstaller();
                    AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline);
                    transactedInstaller.Installers.Add(assemblyInstaller);
                    transactedInstaller.Uninstall(null);
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                }
            }
        }
原文地址:https://www.cnblogs.com/WolfBlog/p/4172005.html