C#编写Windows服务程序的图文详解


当前第2页 返回上一页

在项目中添加2个文件如下(必须是ANSI或者UTF-8无BOM格式):

1)安装脚本Install.bat

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe

Net Start ServiceTest

sc config ServiceTest start= auto

2)卸载脚本Uninstall.bat

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe

3)安装脚本说明

第二行为启动服务。

第三行为设置服务为自动运行。

这2行视服务形式自行选择。

4)脚本调试

如果需要查看脚本运行状况,在脚本最后一行加入pause

五、在C#中对服务进行控制

0)配置目录结构

简历一个新WPF项目,叫WindowsServiceTestUI,添加对System.ServiceProcess的引用。

在WindowsServiceTestUI的bin\Debug目录下建立Service目录。

将WindowsServiceTest的生成目录设置为上面创建的Service目录。

生成后目录结构如下图

1)安装

安装时会产生目录问题,所以安装代码如下:


1

2

3

4

5

6

7

8

string CurrentDirectory = System.Environment.CurrentDirectory;

System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";

Process process = new Process();

process.StartInfo.UseShellExecute = false;

process.StartInfo.FileName = "Install.bat";

process.StartInfo.CreateNoWindow = true;

process.Start();

System.Environment.CurrentDirectory = CurrentDirectory;

2)卸载

卸载时也会产生目录问题,所以卸载代码如下:


1

2

3

4

5

6

7

8

9

string CurrentDirectory = System.Environment.CurrentDirectory;

 

System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";

Process process = new Process();

process.StartInfo.UseShellExecute = false;

process.StartInfo.FileName = "Uninstall.bat";

process.StartInfo.CreateNoWindow = true;

process.Start();

System.Environment.CurrentDirectory = CurrentDirectory;

3)启动

代码如下:


1

2

3

using System.ServiceProcess;

ServiceController serviceController = new ServiceController("ServiceTest");

serviceController.Start();

4)停止


1

2

3

ServiceController serviceController = new ServiceController("ServiceTest");

if (serviceController.CanStop)

serviceController.Stop();

5)暂停/继续


1

2

3

4

5

6

7

ServiceController serviceController = new ServiceController("ServiceTest");

if (serviceController.CanPauseAndContinue){

if (serviceController.Status == ServiceControllerStatus.Running)

serviceController.Pause();

else if (serviceController.Status == ServiceControllerStatus.Paused)

serviceController.Continue();

}

6)检查状态


1

2

3

ServiceController serviceController = new ServiceController("ServiceTest");

 

string Status = serviceController.Status.ToString();

六、调试Windows Service

1)安装并运行服务

2)附加进程

3)在代码中加入断点进行调试

七、总结

本文对Windows service的上述配置都未做详细解释,但是按上述步骤就可以制作可运行的Windows Service,从而达到了工作的需求。

以上就是C#编写Windows服务程序的图文详解的详细内容!

返回前面的内容

相关阅读 >>

asp.net在网站根目录下创建文件夹

.net 玩单反的技巧

.net core中遇到的一些坑的图文详解

关于url后面传中文方法总结

c#实现操作字符串的方法总结

c#如何使用ilgenerator实现动态生成函数的实例

c#关于验证身份证号码的实例分析(正确性)

编写高性能 .net的实例教程

c#中sql参数传入空值出错误和如何解决办法

c#中enum与string的相互转换的示例

更多相关阅读请进入《Windows》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...