C# 实现Window服务实现定时发送邮件

网上有很多关于window服务的讲解,本篇文章将以实例为主,解读如何实现WINDOW服务。

 

环境: VS 2008

1,  新建 WINDOW服务

 

【注:删除program.cs,因为在service1.cs中,我们会定义程序的入口,就不再需要该文件】

2,  项目会自动生成service1.cs 文件,该类继承自ServiceBase类,我这里把文件service1.designer.cs文件内容,复制到service1.cs中,并删除designer文件。在该文件中,重写了方法onStart,onStop等方法。

代码如下:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Diagnostics;

usingSystem.Linq;

usingSystem.ServiceProcess;

usingSystem.Text;

usingSystem.Windows.Forms;

usingSystem.IO;

usingSystem.Net.Mail;

 

namespaceSendeMailService

{

    public partial class Service1 : ServiceBase

    {

        private System.ComponentModel.IContainer components= null;

        private bool servicePaused; //服务停止

        private System.Timers.Timer time; //计时器

        private static readonly stringCurrentPath = Application.StartupPath + "\\";

        public Service1()

        {

            InitializeComponent();

        }

        ///<summary>

        ///进程入口处

        ///</summary>

        static void Main()

        {

            ServiceBase[] myservice= new ServiceBase[] { new Service1() };

            ServiceBase.Run(myservice);

        }

        ///<summary>

        ///开始

        ///</summary>

        ///<paramname="args"></param>

        protected override voidOnStart(string[] args)

        {

            if (servicePaused == false)

            {

                string path = CurrentPath + "start-stop.log";

                if (!File.Exists(path))

                {

                    FileStream create = File.Create(path);

                    create.Close();

                }

                FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);

                StreamWriter sw = new StreamWriter(fs);

                sw.WriteLine("TheService is Starting On" + DateTime.Now.ToShortDateString());

                sw.Flush();

                sw.Close();

                fs.Close();

 

                time = new System.Timers.Timer(3000);

                time.Enabled = true;

                time.Elapsed += this.timeout;

                time.Start();

            }

        }

 

        private void timeout(object sender, EventArgs e)

        {

            MailMessage mail = new MailMessage();

            mail.Subject = "主题,如xxx";

            mail.From = new MailAddress("[email protected]", "kagen");

            mail.To.Add(new MailAddress("[email protected]", "leo")); //可以添加多个收件人

            mail.CC.Add(new MailAddress("[email protected]", "kyo")); //抄送

            mail.Body = "测试邮件,请勿回复!!!!";

            mail.BodyEncoding = System.Text.Encoding.UTF8;

            mail.IsBodyHtml = false;

            mail.Priority = MailPriority.High;

 

            SmtpClient smtp = new SmtpClient("smtp.xxxx.com", 25);

            smtp.EnableSsl = true;

            smtp.UseDefaultCredentials = false;

            smtp.Credentials = new System.Net.NetworkCredential("usrname", "password"); //通行证

            smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //递送方法为 网络

            smtp.Send(mail);

        }

        ///<summary>

        ///结束

        ///</summary>

        protected override void OnStop()

        {

            servicePaused = true;

        }

        ///<summary>

        ///暂停服务

        ///</summary>

        protected override void OnPause()

        {

            servicePaused = true;

        }

 

        ///<summary>

        ///恢复服务

        ///</summary>

        protected override void OnContinue()

        {

            servicePaused = false;

        }

        protected override void Dispose(booldisposing)

        {

            if (disposing &&(components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }

        private void InitializeComponent()

        {

            components = newSystem.ComponentModel.Container();

            this.ServiceName = "Mailxxxxxxx";

 

            this.CanPauseAndContinue = true;

            this.CanStop = true;

            servicePaused = false;

        }

    }

}

 

 

3,  新建安装文件 SEInstall.cs 继承自 Install

 

4,  service1.cs一样,删除designer.cs文件

代码如下:

using System;

using System.Collections;

using System.Collections.Generic;

using System.ComponentModel;

using System.Configuration.Install;

using System.Linq;

 

 

namespace SendeMailService

{

    [RunInstaller(true)]

    public partialclass SEInstaller : Installer

    {

        privateSystem.ComponentModel.IContainer components= null;

        privateSystem.ServiceProcess.ServiceProcessInstallerspInstaller;

        privateSystem.ServiceProcess.ServiceInstaller sInstaller;

        publicSEInstaller()

        {

           InitializeComponent();

        }

 

 

        ///<summary>

        ///清理所有正在使用的资源。

        ///</summary>

        ///<paramname="disposing">如果应释放托管资源,为 true;否则为 false。</param>

        protectedoverride void Dispose(bool disposing)

        {

            if(disposing && (components != null))

            {

               components.Dispose();

            }

           base.Dispose(disposing);

        }

 

        #region 组件设计器生成的代码

 

        ///<summary>

        ///设计器支持所需的方法 - 不要

        ///使用代码编辑器修改此方法的内容。

        ///</summary>

        privatevoid InitializeComponent()

        {

           components = new System.ComponentModel.Container();

           this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller();

           this.sInstaller = new System.ServiceProcess.ServiceInstaller();

            //

            //spInstaller

            //

           this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

           this.spInstaller.Password = null;

           this.spInstaller.Username = null;

            //

            //sInstaller

            //

           this.sInstaller.ServiceName = "Mailxxxxxxx";

           sInstaller.DisplayName = "发送邮件服务";

           sInstaller.Description = "一个定时发送邮件的服务";

           this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

            //

            //Installer1

            //

           this.Installers.AddRange(new System.Configuration.Install.Installer[] {

           this.spInstaller,

           this.sInstaller});

        }

 

        #endregion

    }

}

5,编译成功之后,我们要将生成的exe文件,安装到【服务】

打开CMD-右击【管理员身份运行】-

将路径定位到上图目录下:

定位方式: 1, cd.. 2, cd .. 3,cd C:\Windows\Microsoft.NET\Framework\v2.0.50727

输入如下命令:installutil path[注:pathEXE文件所在目录]

installutile:\xxx.exe

DOS界面会有提示,如果成功,则在【服务】列表会有提示

6,  测试设定的邮箱是否接收到邮件,即可判定是否成功!

7,  卸载服务:Installutil /u path

【注:如果卸载不成功,可以进入注册表删除对应的服务即可。】

services下面找到对应的服务,删除即可。

 

【注:如果服务不能启动,说明程序有问题。可以将编写的程序,先放到 WINFORM程序中测试下】

 

 

 

 

你可能感兴趣的:(C#,service,null,Path,installer,Components)