Create windows service using c#

简介: NOTE: The project name in this sample code is mcWebService which is a spelling mistake. I meant to put mcWinService.

NOTE: The project name in this sample code is mcWebService which is a spelling mistake. I meant to put mcWinService. And now I don't want to change all the screen shots and code all over again. I hope it won't confuse you :).

Ok, its time for one more tutorial. This times pick is Windows Services. Creating Windows Services is not a big deal using C# and Visual Studio. Just follow few simple steps and you are all set to run and test your first Windows Service.

Windows Services is new name for NT Services you used to develop in previous versions of Visual Studio. This tutorial walks you through how to create and use your Windows Services. This Service writes some text to a text file when stop and start the service. The base idea is taken from MSDN but its more elaborated. You can modify it according to your needs.

Step 1. Create Skeleton of the Service

To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.

The result look like this. The Wizard adds WebService1.cs class to your project.

Set your ServiceName to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line this.ServiceName = "mcWinService";

This is the name you will be looking for later :).

The default code of WebService1.cs added by the Wizard looks like here

namespace

mcWebService
{
using
System;
using
System.Collections;
using
System.Core;
using
System.ComponentModel;
using
System.Configuration;
using
System.Data;
using
System.Web.Services;
using
System.Diagnostics;
using
System.ServiceProcess;
public class
WinService1 : System.ServiceProcess.ServiceBase
{
/// <summary>

///
Required designer variable.
/// </summary>

private
System.ComponentModel.Container components;
public
WinService1()
{
// This call is required by the WinForms Component Designer. InitializeComponent();

// TODO: Add any initialization after the InitComponent call
}
// The main entry point for the process
static void
Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
/ create a second service object. For example,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new WinService1(), new
ySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
WinService1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary>

///
Required method for Designer support - do not modify
///
the contents of this method with the code editor.
/// </summary>

private void
InitializeComponent()
{
components =
new
System.ComponentModel.Container();
this
.ServiceName = "WinService1";
}
/// <summary>

///
Set things in motion so your service can do its work.
/// </summary>

protected override void OnStart(string
[] args)
{
// TODO: Add code here to start your service.
}
/// <summary>

///
Stop this service.
/// </summary>

protected override void
OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}


Step 2. Add functionality to your service

As you saw WebService1.cs, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service.

protected

override void OnStart(string [] args)
{
FileStream fs =
new
FileStream(@"c:\temp\mcWindowsService.txt" ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new
StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" mcWindowsService: Service Started \n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
/// <summary>

///
Stop this service.
/// </summary>

protected override void
OnStop()
{
FileStream fs =
new
FileStream(@"c:\temp\mcWindowsService.txt" ,
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter =
new
StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" mcWindowsService: Service Stopped \n"); m_streamWriter.Flush();
m_streamWriter.Close();

 
Step 3: Install and Run the Service

Build of this application makes one exe, mcWinService.exe. You need to call installutil to
egister this service from command line.
installutil C:\mcWebService\bin\Debug\mcWebService.exe
You use /u option to uninstall the service.
installutil /u C:\mcWebService\bin\Debug\mcWebService.exe
Run the application

Step 4: Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer. 

Under Services and Applications, you will see the service mcWinService. Start and Stop menu item starts and stops the service.

Step 5: Test the Service

Go to your temp directory and see if text file is there with contents or not.

That's it.

目录
相关文章
|
4月前
|
Linux C++ Windows
【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数
【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数
【Azure 应用服务】Azure App Service(Windows)环境中如何让.NET应用调用SAP NetWeaver RFC函数
|
25天前
|
安全 Windows
【Azure Cloud Service】在Windows系统中抓取网络包 ( 不需要另外安全抓包工具)
通常,在生产环境中,为了保证系统环境的安全和纯粹,是不建议安装其它软件或排查工具(如果可以安装,也是需要走审批流程)。 本文将介绍一种,不用安装Wireshark / tcpdump 等工具,使用Windows系统自带的 netsh trace 命令来获取网络包的步骤
65 32
|
1月前
|
C# Windows
【Azure App Service】在App Service for Windows上验证能占用的内存最大值
根据以上测验,当使用App Service内存没有达到预期的值,且应用异常日志出现OutOfMemory时,就需要检查Platform的设置是否位64bit。
42 11
|
20天前
|
数据库连接 数据库 C#
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(上)
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(上)
|
20天前
|
数据库连接 数据库 C#
Windows下C# 通过ADO.NET方式连接南大通用GBase 8s数据库(下)
本文接续前文,深入讲解了在Windows环境下使用C#和ADO.NET操作南大通用GBase 8s数据库的方法。通过Visual Studio 2022创建项目,添加GBase 8s的DLL引用,并提供了详细的C#代码示例,涵盖数据库连接、表的创建与修改、数据的增删查改等操作,旨在帮助开发者提高数据库管理效率。
|
4月前
|
Java 应用服务中间件 开发工具
[App Service for Windows]通过 KUDU 查看 Tomcat 配置信息
[App Service for Windows]通过 KUDU 查看 Tomcat 配置信息
|
4月前
|
Java 应用服务中间件 Windows
【App Service for Windows】为 App Service 配置自定义 Tomcat 环境
【App Service for Windows】为 App Service 配置自定义 Tomcat 环境
|
4月前
|
PHP Windows
【Azure App Service for Windows】 PHP应用出现500 : The page cannot be displayed because an internal server error has occurred. 错误
【Azure App Service for Windows】 PHP应用出现500 : The page cannot be displayed because an internal server error has occurred. 错误
|
4月前
|
PHP 开发工具 git
【Azure 应用服务】在 App Service for Windows 中自定义 PHP 版本的方法
【Azure 应用服务】在 App Service for Windows 中自定义 PHP 版本的方法
|
4月前
|
开发者 iOS开发 C#
Uno Platform 入门超详细指南:从零开始教你打造兼容 Web、Windows、iOS 和 Android 的跨平台应用,轻松掌握 XAML 与 C# 开发技巧,快速上手示例代码助你迈出第一步
【8月更文挑战第31天】Uno Platform 是一个基于 Microsoft .NET 的开源框架,支持使用 C# 和 XAML 构建跨平台应用,适用于 Web(WebAssembly)、Windows、Linux、macOS、iOS 和 Android。它允许开发者共享几乎全部的业务逻辑和 UI 代码,同时保持原生性能。选择 Uno Platform 可以统一开发体验,减少代码重复,降低开发成本。安装时需先配置好 Visual Studio 或 Visual Studio for Mac,并通过 NuGet 或官网下载工具包。
396 0