c#使用sc命令注册开发Windows服务

来源:互联网 发布:oracle12c连接数据库 编辑:程序博客网 时间:2024/06/09 18:27

   Windows服务的开发如果中规中矩的话开发测试安装都十分繁琐,现备忘一个简易的方案。

   主要原理也很简单,就是利用Windows自带的服务管理命令sc进行注册,运行。


using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.ServiceProcess;using System.Text;namespace wiffiMinitorSvr{    static class Program    {        static string excuteCmd(string cmd)        {            Console.WriteLine("will be excute command {0}", cmd);            Process proc = new Process();            proc.StartInfo.FileName = "cmd.exe";            proc.StartInfo.UseShellExecute = false;            proc.StartInfo.RedirectStandardInput = false;            proc.StartInfo.RedirectStandardOutput = true;            proc.StartInfo.RedirectStandardError = true;            proc.StartInfo.CreateNoWindow = true;            proc.StartInfo.Arguments = "/c " + cmd;            proc.Start();            proc.WaitForExit();            string ret = proc.StandardOutput.ReadToEnd() + proc.StandardError.ReadToEnd();            Console.WriteLine(ret);            return ret;        }        /// <summary>        /// The main entry point for the application.        /// </summary>        static void Main(string[] args)        {            FileStream os = null;            try            {                os = new FileStream("d:\\wiffiMonitor.log", FileMode.Create);                Console.SetOut(new StreamWriter(os));                Console.WriteLine("log will begin --------");            }            catch (Exception e)            {                Console.WriteLine(e);                return;            }            string result = excuteCmd("sc qc wiffiMonitor");            if (result.IndexOf("1060") == -1)            {                try                {                    Console.WriteLine("will be run service ...");                    ServiceBase.Run(new ServiceBase[]{                                new wiffiMinitorSvr()                            });                    Console.WriteLine("serivce running ....");                }                catch (Exception e)                {                    Console.WriteLine(e);                }                if (null != os)                    os.Close();                return;            }            try            {                var path = Process.GetCurrentProcess().MainModule.FileName;                string cmd = String.Format("sc create wiffiMonitor binPath= \"{0}\" DisplayName= wiffi助手 start= auto", path);                excuteCmd(cmd);                excuteCmd("sc start wiffiMonitor r");                excuteCmd("shutdown -r");            }            catch (Exception e)            {                Console.WriteLine(e.ToString());            }            if (null != os)                os.Close();        }    }}


0 0
原创粉丝点击