C# 创建 Windows Service 项目

C# 创建 WindowsService 服务项目
image
空白处,右键选择“添加安装程序”
image
可以看到两个控件,点击右击第一个控件,打开属性设计器,将其中的Account设置为LocalSystem(本地服务),
image
接下来,右击上面的第二个控件,打开属性界面,设置ServiceName,和将其中的StratType设置为Automatic,
image

public partial class Service1 : ServiceBase
{
    private readonly Timer _MyTimer;
    public Service1()
    {
        InitializeComponent();
        _MyTimer = new Timer(10*1000); //10秒钟启动一次
        _MyTimer.Elapsed += _MyTimerElapsed;
    }

    protected override void OnStart(string[] args)
    {
        _MyTimer.Start(); 
        WriteLog("Service1.OnStart");
    }

    protected override void OnStop()
    {
        _MyTimer.Stop();
        WriteLog("Service1.OnStop");
    }

    internal void _MyTimerElapsed(object sender, ElapsedEventArgs e)
    {
        WriteLog("开始执行了");
    }


    public void WriteLog(string msg)
    {
        string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        try
        {
            using (StreamWriter sw = File.AppendText(logPath))
            {
                sw.WriteLine("消息:" + msg);
                sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sw.WriteLine("**************************************************");
                sw.WriteLine();
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
        }
        catch (IOException e)
        {
            using (StreamWriter sw = File.AppendText(logPath))
            {
                sw.WriteLine("异常:" + e.Message);
                sw.WriteLine("时间:" + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss"));
                sw.WriteLine("**************************************************");
                sw.WriteLine();
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
        }
    }

}

安装脚本 0.Install.bat

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe
Net Start ServiceTest
sc config ServiceTest start= auto
pause

卸载脚本 1.Uninstall.bat

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe
posted @ 2024-08-12 13:09  VipSoft  阅读(62)  评论(0)    收藏  举报