C# 服务 调试、正式使用两便的模板

转自:http://www.mysticboy.cn/article.asp?id=100

常驻内存的程序是一些监控或者数据处理的项目中最常用的程序, 有的人做成控制台程序,长期开着, 可是这要登录进去,然后自动运行,必须保持用户在登录状态,这样唯一的好处是能看到调试信息(console.writeline输出的东西),很多人都这么干, 我就碰到好几个大项目,比如某省的高速公路收费等。
服务的好处和不好处,一对比就出来了, 服务不用用户登录就能后台运行,但是看不到实时信息。 很不爽。 所以我在这里献丑,弄了一个二转子。呵呵。
这个程序即可以作为服务,也可以作为控制台, 你想调试的时候 加参数/debug 你想作为服务的时候  /install 然后后台运行。
如果你感兴趣, 请看下面代码。  因为代码比描述来的更直接。 哈哈
新建控制台项目  添加一个 叫MSG2DB的类文件, 粘贴如下内容。
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;
using System.Reflection;
namespace MSG2DBServer
{
    public class MSG2DB : ServiceBase
    {
        public MSG2DB()
        {
            this.ServiceName = MyServiceName;
        }
        public  static  string MyServiceName
        {
            get { return   Assembly.GetExecutingAssembly().GetName().Name; }
        }
        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
              MSG2DBWorker.Do();
        }
        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
           MSG2DBWorker.PleaseStop=true ;
        }
    }
}
修改 Program.cs的代码为 如下代码
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;
using System.Reflection;
namespace MSG2DBServer
{
    class Program
    {
        static void Main(string[] args)
        {
            bool RunAsService = true  ;
            if (args.Length > 0)
            {
                System.Runtime.p
                RunAsService=false ;
                switch (args[0].ToLower())
                {
                    case  "/debug":
                        MSG2DBWorker.Do();
                        break;
                    case "/install":
                     Console.WriteLine("正在准备安装服务");
                     Console.WriteLine(CommandDo.Execute(string.Format(
                            "sc create {0}  binPath= \"{1}\"  start= auto",
                            MSG2DB.MyServiceName, Assembly.GetExecutingAssembly().Location
                            )));
                     Console.WriteLine(CommandDo.Execute(" sc start " + MSG2DB.MyServiceName));
                     Console.WriteLine("安装完成");
                        break;
                    case "/uninstall":
                        Console.WriteLine("正在卸载安装服务");
                        Console.WriteLine(CommandDo.Execute("sc stop " + MSG2DB.MyServiceName));
                        Console.WriteLine(CommandDo.Execute("sc delete " + MSG2DB.MyServiceName));
                        Console.WriteLine("卸载完成");
                        break;
                    case "/?":
                    case "/help":
                        Console.WriteLine("/install 安装此服务  /uninstall 卸载此服务  /? 或者 /help 显示当前信息 ");
                        break;
                    default:
                        Console.WriteLine(CommandDo.Execute("sc " + args[0] + " " + MSG2DB.MyServiceName));
                        break;
                }
              }
              if (RunAsService)
              {
                  ServiceBase[] ServicesToRun;
                  ServicesToRun = new ServiceBase[] { new MSG2DB() };
                  ServiceBase.Run(ServicesToRun);
              }
        }
    }
}
添加一个执行dos命令的文件,呵呵, 网上找的
using System;
using System.Text;
using System.Diagnostics;
namespace MSG2DBServer
{
/**//// <summary>
/// DOS命令输出类
/// </summary>
public class CommandDo
{
  /**//// <summary>
  /// 执行DOS命令,返回DOS命令的输出
  /// </summary>
  /// <param name="dosCommand">dos命令</param>
  /// <returns>返回输出,如果发生异常,返回空字符串</returns>
  public static string Execute(string dosCommand)
  {
   return Execute(dosCommand, 6 * 1000);
  }
  /**//// <summary>
  /// 执行DOS命令,返回DOS命令的输出
  /// </summary>
  /// <param name="dosCommand">dos命令</param>
  /// <param name="milliseconds">等待命令执行的时间(单位:毫秒),如果设定为0,则无限等待</param>
  /// <returns>返回输出,如果发生异常,返回空字符串</returns>
  public static string Execute(string dosCommand, int milliseconds)
  {
   string output = "";     //输出字符串
   if (dosCommand != null && dosCommand != "")
   {
    Process process = new Process();     //创建进程对象
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "cmd.exe";      //设定需要执行的命令
    startInfo.Arguments = "/C " + dosCommand;   //设定参数,其中的“/C”表示执行完命令后马上退出
    startInfo.UseShellExecute = false;     //不使用系统外壳程序启动
    startInfo.RedirectStandardInput = false  ;   //不重定向输入
    startInfo.RedirectStandardOutput = true;   //重定向输出
    startInfo.CreateNoWindow = true;     //不创建窗口
    process.StartInfo = startInfo;
    try
    {
     if (process.Start())       //开始进程
     {
      if (milliseconds == 0)
       process.WaitForExit();     //这里无限等待进程结束
      else
       process.WaitForExit(milliseconds);  //这里等待进程结束,等待时间为指定的毫秒
      output = process.StandardOutput.ReadToEnd();//读取进程的输出
     }
    }
    catch
    {
    }
    finally
    {
     if (process != null)
      process.Close();
    }
   }
   return output;
  }
}
}
添加 一个你的程序文件 , 这个文件里 我们将写入 我们要执行的代码。 比如循环啦。 等等哈吉玛塔的东西
using System;
using System.Collections.Generic;
using System.Text;
namespace MSG2DBServer
{
    public static class MSG2DBWorker
    {
       public static  void Do()
       {
           do
           {
               System.Threading.Thread.Sleep(100);
           } while (PleaseStop==false );
           Stoped = true;
       }
       private static bool _PleaseStop;
       /**//// <summary>
       /// 需要停止
       /// </summary>
       public static bool PleaseStop
    {
        get { return _PleaseStop;}
        set { _PleaseStop = value;}
    }
       private static bool _Stoped;
    /**//// <summary>
    /// 我停止了
    /// </summary>
       public static bool Stoped
    {
        get { return _Stoped; }
        set { _Stoped = value; }
    }
    }
}
https://files.cnblogs.com/MysticBoy/MSG2DBServer.rar

原文地址:https://www.cnblogs.com/bennylam/p/1590385.html