C#Windows服务程序开发实例介绍

开发 后端
C#Windows服务程序开发实例主要向你介绍一个用于开机启动其他程序的Windows服务,那么具体的实现的步骤是什么呢?一下的C#Windows服务程序开发实例就向你一一介绍。

C#Windows服务程序开发实例程序的目的和用途:

很多开机启动程序仅仅加在启动项里面,只有登陆后才真正启动。windows服务在开机未进行用户登录前就启动了。正是利用这一点,解决一些服务器自动重启后特定软件也自动启动的问题。

C#Windows服务程序开发1.

新建一个服务项目 visual C#----windows----windows服务;

C#Windows服务程序开发2.

添加一个dataset(.xsd),用于存储启动目标的路径,日志路径等。

在dataset可视化编辑中,添加一个datatable,包含两列 StartAppPath 和 LogFilePath。分别用于存储目标的路径、日志路径。

我认为利用dataset.xsd存储配置参数的优势在于可以忽略xml解析的具体过程直接使用xml文件。

在dataset中 提供了ReadXml方法用于读取xml文件并将其转换成内存中的一张datatable表,数据很容易取出来!同样,WriteXml方法用于存储为xml格式的文件,也仅仅需要一句话而已。

C#Windows服务程序开发3.

program.cs文件 作为程序入口,代码如下:

  1. view plaincopy to clipboardprint?  
  2. using System.Collections.Generic;     
  3. using System.ServiceProcess;     
  4. using System.Text;     
  5.     
  6. namespace WindowsServices_AutoStart     
  7. {     
  8. static class Program     
  9. {     
  10. /// ﹤summary﹥     
  11. /// 应用程序的主入口点。     
  12. /// ﹤/summary﹥     
  13. static void Main()     
  14. {     
  15. ServiceBase[] ServicesToRun;     
  16.     
  17. // 同一进程中可以运行多个用户服务。若要将     
  18. // 另一个服务添加到此进程中,请更改下行以     
  19. // 创建另一个服务对象。例如,     
  20. //     
  21. //   ServicesToRun = new ServiceBase[] {  
  22. new Service1(), new MySecondUserService()};     
  23. //     
  24. ServicesToRun = new ServiceBase[] {   
  25. new WindowsServices_AutoStart() };     
  26.     
  27. ServiceBase.Run(ServicesToRun);     
  28. }     
  29. }     
  30. }    
  31. using System.Collections.Generic;  
  32. using System.ServiceProcess;  
  33. using System.Text;  
  34.  
  35. namespace WindowsServices_AutoStart  
  36. {  
  37. static class Program  
  38. {  
  39. /// ﹤summary﹥  
  40. /// 应用程序的主入口点。  
  41. /// ﹤/summary﹥  
  42. static void Main()  
  43. {  
  44. ServiceBase[] ServicesToRun;  
  45.  
  46. // 同一进程中可以运行多个用户服务。若要将  
  47. // 另一个服务添加到此进程中,请更改下行以  
  48. // 创建另一个服务对象。例如,  
  49. //  
  50. //   ServicesToRun = new ServiceBase[] {  
  51. new Service1(), new MySecondUserService()};  
  52. //  
  53. ServicesToRun = new ServiceBase[] {  
  54.  new WindowsServices_AutoStart() };  
  55.  
  56. ServiceBase.Run(ServicesToRun);  
  57. }  
  58. }  
  59. }  

C#Windows服务程序开发4.

service.cs主文件,代码如下:

  1. view plaincopy to clipboardprint?  
  2. using System;     
  3. using System.Collections.Generic;     
  4. using System.ComponentModel;     
  5. using System.Data;     
  6. using System.IO;     
  7. using System.Diagnostics;     
  8. using System.ServiceProcess;     
  9. using System.Text;     
  10.     
  11. namespace WindowsServices_AutoStart     
  12. {     
  13. public partial class   
  14. WindowsServices_AutoStart : ServiceBase     
  15. {     
  16. public WindowsServices_AutoStart()     
  17. {     
  18. InitializeComponent();     
  19. }     
  20. string StartAppPath ="";  
  21.  //@"F:\00.exe";     
  22. string LogFilePath ="";  
  23. // @"f:\WindowsService.txt";     
  24. protected override void OnStart(string[] args)     
  25. {     
  26. string exePath = System.Threading.  
  27. Thread.GetDomain().BaseDirectory;     
  28. //     
  29. if (!File.Exists(exePath + @"\ServiceAppPath.xml"))     
  30. {     
  31. dsAppPath ds = new dsAppPath();     
  32. object[] obj=new object[2];     
  33. obj[0]="0";     
  34. obj[1]="0";     
  35. ds.Tables["dtAppPath"].Rows.Add(obj);     
  36. ds.Tables["dtAppPath"].WriteXml(  
  37. exePath + @"\ServiceAppPath.xml");     
  38. return;     
  39. }     
  40. try    
  41. {     
  42. dsAppPath ds = new dsAppPath();     
  43. ds.Tables["dtAppPath"].ReadXml(  
  44. exePath + @"\ServiceAppPath.xml");     
  45. DataTable dt = ds.Tables["dtAppPath"];     
  46. StartAppPath = dt.Rows[0]  
  47. ["StartAppPath"].ToString();     
  48. LogFilePath = dt.Rows[0]  
  49. ["LogFilePath"].ToString();     
  50. }     
  51. catch { return; }     
  52.      
  53. if (File.Exists(StartAppPath))     
  54. {     
  55. try    
  56. {     
  57. Process proc = new Process();     
  58. proc.StartInfo.FileName = StartAppPath; //注意路径     
  59. //proc.StartInfo.Arguments = "";     
  60. proc.Start();     
  61. }     
  62. catch (System.Exception ex)     
  63. {     
  64. //MessageBox.Show(this, "找不到帮助文件路径。  
  65. 文件是否被改动或删除?\n" + ex.Message, "提示",  
  66.  MessageBoxButtons.OK, MessageBoxIcon.Information);     
  67. }     
  68. FileStream fs = new FileStream(LogFilePath,   
  69. FileMode.OpenOrCreate, FileAccess.Write);     
  70. StreamWriter m_streamWriter = new StreamWriter(fs);     
  71. m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);     
  72. m_streamWriter.WriteLine("WindowsService:   
  73. Service Started" + DateTime.Now.ToString() + "\n");     
  74. m_streamWriter.Flush();     
  75. m_streamWriter.Close();     
  76. fs.Close();     
  77. }     
  78. }     
  79.     
  80. protected override void OnStop()     
  81. {     
  82. try    
  83. {     
  84. // TODO: 在此处添加代码以执行停止服务所需的关闭操作。     
  85. FileStream fs = new FileStream(LogFilePath,  
  86.  FileMode.OpenOrCreate, FileAccess.Write);     
  87. StreamWriter m_streamWriter = new StreamWriter(fs);     
  88. m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);     
  89. m_streamWriter.WriteLine("WindowsService:  
  90.  Service Stopped " + DateTime.Now.ToString() + "\n");     
  91. m_streamWriter.Flush();     
  92. m_streamWriter.Close();     
  93. fs.Close();     
  94. }     
  95. catch    
  96. {     
  97.     
  98. }     
  99. }     
  100. }     
  101. }    
  102. using System;  
  103. using System.Collections.Generic;  
  104. using System.ComponentModel;  
  105. using System.Data;  
  106. using System.IO;  
  107. using System.Diagnostics;  
  108. using System.ServiceProcess;  
  109. using System.Text;  
  110.  
  111. namespace WindowsServices_AutoStart  
  112. {  
  113. public partial class   
  114. WindowsServices_AutoStart : ServiceBase  
  115. {  
  116. public WindowsServices_AutoStart()  
  117. {  
  118. InitializeComponent();  
  119. }  
  120. string StartAppPath ="";   
  121. //@"F:\00.exe";  
  122. string LogFilePath ="";  
  123. // @"f:\WindowsService.txt";  
  124. protected override void OnStart(string[] args)  
  125. {  
  126. string exePath = System.  
  127. Threading.Thread.GetDomain().BaseDirectory;  
  128. //  
  129. if (!File.Exists(exePath + @"\ServiceAppPath.xml"))  
  130. {  
  131. dsAppPath ds = new dsAppPath();  
  132. object[] obj=new object[2];  
  133. obj[0]="0";  
  134. obj[1]="0";  
  135. ds.Tables["dtAppPath"].Rows.Add(obj);  
  136. ds.Tables["dtAppPath"].WriteXml(  
  137. exePath + @"\ServiceAppPath.xml");  
  138. return;  
  139. }  
  140. try 
  141. {  
  142. dsAppPath ds = new dsAppPath();  
  143. ds.Tables["dtAppPath"].ReadXml(  
  144. exePath + @"\ServiceAppPath.xml");  
  145. DataTable dt = ds.Tables["dtAppPath"];  
  146. StartAppPath = dt.Rows[0]  
  147. ["StartAppPath"].ToString();  
  148. LogFilePath = dt.Rows[0]  
  149. ["LogFilePath"].ToString();  
  150. }  
  151. catch { return; }  
  152.  
  153. if (File.Exists(StartAppPath))  
  154. {  
  155. try 
  156. {  
  157. Process proc = new Process();  
  158. proc.StartInfo.FileName = StartAppPath; //注意路径  
  159. //proc.StartInfo.Arguments = "";  
  160. proc.Start();  
  161. }  
  162. catch (System.Exception ex)  
  163. {  
  164. //MessageBox.Show(this, "  
  165. 找不到帮助文件路径。文件是否被改动或删除?\n"  
  166.  + ex.Message, "提示", MessageBoxButtons.OK,  
  167.  MessageBoxIcon.Information);  
  168. }  
  169. FileStream fs = new FileStream(LogFilePath,  
  170.  FileMode.OpenOrCreate, FileAccess.Write);  
  171. StreamWriter m_streamWriter = new StreamWriter(fs);  
  172. m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);  
  173. m_streamWriter.WriteLine("WindowsService:   
  174. Service Started" + DateTime.Now.ToString() + "\n");  
  175. m_streamWriter.Flush();  
  176. m_streamWriter.Close();  
  177. fs.Close();  
  178. }  
  179. }  
  180.  
  181. protected override void OnStop()  
  182. {  
  183. try 
  184. {  
  185. // TODO: 在此处添加代码以执行停止服务所需的关闭操作。  
  186. FileStream fs = new FileStream(LogFilePath,   
  187. FileMode.OpenOrCreate, FileAccess.Write);  
  188. StreamWriter m_streamWriter = new StreamWriter(fs);  
  189. m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);  
  190. m_streamWriter.WriteLine("WindowsService:   
  191. Service Stopped " + DateTime.Now.ToString() + "\n");  
  192. m_streamWriter.Flush();  
  193. m_streamWriter.Close();  
  194. fs.Close();  
  195. }  
  196. catch 
  197. {  
  198.  
  199. }  
  200. }  
  201. }  

C#Windows服务程序开发5.

启动调试,成功时也会弹出一个对话框大致意思是提示服务需要安装。

C#Windows服务程序开发6.

把Debug文件夹下面的.exe执行程序,安装为windows系统服务,安装方法网上很多介绍。我说一种常用的:

C#Windows服务程序开发之安装服务

访问项目中的已编译可执行文件所在的目录。

用项目的输出作为参数,从命令行运行 InstallUtil.exe。在命令行中输入下列代码: 

installutil yourproject.exe

C#Windows服务程序开发之卸载服务 

用项目的输出作为参数,从命令行运行 InstallUtil.exe。 
installutil /u yourproject.exe

至此,整个服务已经编写,编译,安装完成,你可以在控制面板的管理工具的服务中,看到你编写的服务。

C#Windows服务程序开发7.

安装好了之后在系统服务列表中可以管理服务,这时要注意将服务的属性窗口----登陆----“允许于桌面交互”勾选!这样才能在启动了你要的目标程序后不单单存留于进程。在桌面上也看得到。

C#Windows服务程序开发8.

关于卸载服务,目前有两个概念:一是禁用而已;一是完全删除服务。 前者可以通过服务管理窗口直接完成。后者则需要进入注册表

“HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services”找到服务名称的文件夹,整个删掉,重新启动电脑后,服务消失。

C#Windows服务程序开发9.

扩展思考:经过修改代码,还可以实现:启动目标程序之前,检测进程中是否存在目标程序,存在则不再次启动。

C#Windows服务程序开发的实例的基本内容就向你,希望对你学习和理解C#Windows服务程序开发有所帮助。

【编辑推荐】

  1. C#Windows服务程序开发之Windows服务浅析
  2. C#Windows服务程序安装浅析
  3. C#Windows服务程序开发的体会
  4. C#启动windows服务的方法浅析
  5. C#windows服务状态改变操作浅析
责任编辑:仲衡 来源: 百度空间
相关推荐

2009-08-14 14:17:16

C#Windows服务

2009-08-14 10:50:09

Windows服务介绍

2009-08-14 14:25:09

Windows服务程序

2009-08-14 15:19:38

Windows服务程序Windows服务

2009-08-14 15:54:50

Windows服务程序C#Windows服务

2009-08-14 14:45:03

C#Windows服务

2009-08-14 15:06:08

Windows服务程序

2009-08-14 15:47:18

C#Windows服务

2009-08-14 16:48:39

C#Windows服务

2009-08-14 13:41:13

C#Windows服务

2009-08-14 17:27:30

C#Windows应用

2009-08-14 17:36:20

C#Windows应用

2009-08-14 14:53:55

WINDOWS服务交互

2009-08-14 17:55:52

C#Windows应用

2009-08-14 17:43:20

C#Windows应用

2009-08-14 11:15:19

文件监视C#Windows服务

2009-08-14 16:13:25

C#windows服务

2009-08-14 18:00:22

C#Windows应用

2009-08-14 18:04:59

C#Windows应用

2009-08-14 17:51:32

C#Windows应用
点赞
收藏

51CTO技术栈公众号