C#程序注册成服务
某些时候我们需要一个程序在电脑开机后就自动启动,无界面运行在后台。比如数据上传功能,我们需要在电脑开机后程序就自动启动,上传我们需要的数据,而不是每次开机都要手动去运行程序。
1、新建一个项目,该项目实现上传数据的功能。
该上传功能我们用定时输入日志来模拟
public class UploadDataUtil
{
private static System.Threading.Timer t1;//定时器
private static int rate = 60 * 1000;//同步频率
private static int index = 0;
/// <summary>
/// 开启数据上传线程
/// </summary>
public static void startUpLoadDataThread()
{
//开启定时器
t1 = new System.Threading.Timer(new TimerCallback(startTask), null, 0, rate);
}
/// <summary>
/// 开始任务
/// </summary>
private static void startTask(object obj)
{
//上传数据代码(此处输出日志)
writeLog((index++).ToString());
}
/// <summary>
/// 写日志到日志文件
/// </summary>
/// <param name="text">文件内容</param>
private static void writeLog(string text)
{
FileStream fs = null;
try
{
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "UploadData.txt";//日志文件路径
string content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + text + "\n";
//将待写的入数据从字符串转换为字节数组
Encoding encoder = Encoding.UTF8;
byte[] bytes = encoder.GetBytes(content);
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
fs = File.OpenWrite(filePath);
//设定书写的开始位置为文件的末尾
fs.Position = fs.Length;
//将待写入内容追加到文件末尾
fs.Write(bytes, 0, bytes.Length);
}
catch (Exception)
{
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
}
2、新建一个windows服务程序,这是一个服务程序,我们在这个程序中引用上一个项目,调用上传数据的功能。
2.1、在Service.cs的设计界面右键【添加安装程序】
2.2、点击serviceProcessInstaller1,将Account改为LocalSystem(服务属性系统级别),如下图所示:
2.3、点击serviceInstaller1,为服务添加描述信息(Description),修改服务名称(ServiceName),将服务启动类型(StartType)设置为自动(Automatic)
2.4、在Service1的代码中调用数据上传功能
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
/// <summary>
/// 服务启动
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
//开启数据上传线程
UploadData.UploadDataUtil.startUpLoadDataThread();
}
/// <summary>
/// 服务停止
/// </summary>
protected override void OnStop()
{
}
}
至此windows服务程序创建完毕
3、新建一个项目,将上一步创建的服务程序安装到计算机。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
try
{
string serviceFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "UploadDataService.exe";//服务文件路径
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
}
MessageBox.Show("服务注册成功");
}
catch (Exception)
{
}
}
}
4、以管理员方式运行UploadServiceInstall.exe,点击【安装服务】按钮
4.1、服务注册成功,打开windows服务,可以找到【UploadDataService】服务,右键服务【启动】,启动之后在我们的项目下面会看到日志文件。
至此,上传数据的程序就注册成windows服务了,之后电脑每次开机,服务都会自动启动,不需要我们手动运行程序了。
更多内容请关注微信公众号【CSharp编程学习】
下一篇:C#实现串口通讯