1.打开VS建一个Windows 服务
2.下一步,填好项目名称和项目保存的地址
3.创建之后,右击、选择添加安装程序
4.添加安装程序之后会出现‘serviceInstaller1’=>在此控件上右键=>选择属性=>更改服务名、服务描述、服务显示名。
5.写代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace MyWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
timer.Interval = 1000*60*60;//每60分钟执行一次
timer.Enabled = true;
}
private void TimedEvent(object sender, ElapsedEventArgs e)
{
WriteLog("开始发送");
//发件人地址
MailAddress from = new MailAddress("123@qq.com");
MailMessage message = new MailMessage();
message.Body = "test";
message.IsBodyHtml = true;
message.BodyEncoding = System.Text.Encoding.UTF8;
//收件人地址
message.To.Add("321@outlook.com");
message.Subject = "青海长云暗雪山,孤城遥望玉门关。黄沙百战穿金甲,不破楼兰终不还!";
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.From = from;
//附件
Attachment amAnnex = new Attachment(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt");
message.Attachments.Add(amAnnex);
SmtpClient client = new SmtpClient();
client.EnableSsl = true;
client.Host = "smtp.qq.com";
client.Port = 587;
//邮箱账户和密码
client.Credentials = new System.Net.NetworkCredential("123@qq.com", "123");
try
{
client.Send(message);
}
catch (Exception ex)
{
string mssage = ex.ToString();
}
}
protected override void OnStart(string[] args)
{
this.WriteLog("【服务启动】");
}
protected override void OnStop()
{
this.WriteLog("【服务停止】");
}
protected override void OnShutdown()
{
this.WriteLog("【计算机关闭】");
}
#region 记录日志
/// <summary>
/// 记录日志
/// </summary>
/// <param name="msg"></param>
private void WriteLog(string msg)
{
//该日志文件会存在windows服务程序目录下
string path = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
FileStream fs;
fs = File.Create(path);
fs.Close();
}
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(DateTime.Now.ToString() + " " + msg);
}
}
}
#endregion
}
}
6.用管理员打开cmd=>%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe F:\MyCode\MyWindowsService\MyWindowsService\bin\Debug\MyWindowsService.exe
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe 是你Framework版本下的InstallUtil.exe路径
F:\MyCode\MyWindowsService\MyWindowsService\bin\Debug\MyWindowsService.exe 是你程序的路径
7.启动服务用 net start MyService
停止服务用 net stop MyService
删除服务用 sc delete MyService
MyService为服务名