软件编程
位置:首页>> 软件编程>> C#编程>> 利用C#编写一个Windows服务程序的方法详解

利用C#编写一个Windows服务程序的方法详解

作者:小恶魔@  发布时间:2022-08-09 20:24:03 

标签:C#,Windows,服务

1.添加引用Windows服务(.NET Framework)

利用C#编写一个Windows服务程序的方法详解

2.输入项目名称,选择安装位置,,选择安装框架版本;创建。

利用C#编写一个Windows服务程序的方法详解

3.找到MyService.cs ,右击‘查看代码’

利用C#编写一个Windows服务程序的方法详解

利用C#编写一个Windows服务程序的方法详解

添加如下代码:

public partial class MyService : ServiceBase
   {
       public MyService()
       {
           InitializeComponent();
       }
       string filePath = @"D:\MyServiceLog.txt";
       protected override void OnStart(string[] args)
       {//服务启动时,执行该方法
           using (FileStream stream = new FileStream(filePath,FileMode.Append))
           using (StreamWriter writer = new StreamWriter(stream))
           {
               writer.WriteLine($"{DateTime.Now},服务启动!");
           }
       }
       protected override void OnStop()
       {//服务关闭时,执行该方法
           using (FileStream stream = new FileStream(filePath,FileMode.Append))
           using (StreamWriter writer = new StreamWriter(stream))
           {
               writer.WriteLine($"{DateTime.Now},服务停止!");
           }
       }
   }

4.双击MyService.cs,在出现的界面中右击–>选择“添加安装程序”。

利用C#编写一个Windows服务程序的方法详解

点击后,会自动生产连个控件,sericcelnstaller1 和sericeProcessInstaller1

利用C#编写一个Windows服务程序的方法详解

5.分别设置两个控件的属性

右击serviceInstaller1 点击属性

利用C#编写一个Windows服务程序的方法详解

分别设置:服务安装的描述,服务的名称,启动的类型 。

利用C#编写一个Windows服务程序的方法详解

在serviceProcessInstaller1 ,设置Account(服务属性系统级别),设置“本地服务”

利用C#编写一个Windows服务程序的方法详解

6.找到项目,右击“重新生成”。

利用C#编写一个Windows服务程序的方法详解

7.在同一个解决方案下,添加Windows From项目应用窗体:

①点击“添加”,新建项目,选择Windows窗体应用。要注意添加时,选择的路径,是否在同一个解决方案目录下。

利用C#编写一个Windows服务程序的方法详解

利用C#编写一个Windows服务程序的方法详解

利用C#编写一个Windows服务程序的方法详解

8.找到Form设计窗体,添加控件如图。控件工具箱在菜单栏–>视图–>找到‘工具箱’。如图所示

利用C#编写一个Windows服务程序的方法详解

利用C#编写一个Windows服务程序的方法详解

9.Form窗体中,单击空白窗体,按F7进入命令界面。添加如下代码:

public partial class Form2 : Form
   {
       public Form2()
       {
           InitializeComponent();
       }
       string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";//MyWindowsService.exe 是项目名称对应的服务
       string serviceName = "DemoService"; //这里时服务名,是第五点中,设置的名称,要对应好

private void button1_Click(object sender, EventArgs e)
       {
           try
           {
               System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
               myProcess.StartInfo.FileName = "cmd.exe";//启动cmd命令
               myProcess.StartInfo.UseShellExecute = false;//是否使用系统外壳程序启动进程
               myProcess.StartInfo.RedirectStandardInput = true;//是否从流中读取
               myProcess.StartInfo.RedirectStandardOutput = true;//是否写入流
               myProcess.StartInfo.RedirectStandardError = true;//是否将错误信息写入流
               myProcess.StartInfo.CreateNoWindow = true;//是否在新窗口中启动进程
               myProcess.Start();//启动进程
               //myProcess.StandardInput.WriteLine("shutdown -s -t 0");//执行关机命令
               myProcess.StandardInput.WriteLine("shutdown -r -t 60");//执行重启计算机命令
           }
           catch (Exception) { }
       }

//停止服务
       private void button2_Click(object sender, EventArgs e)
       {
           try
           {
               if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
           }
           catch (Exception ex)
           {
               MessageBox.Show("无法停止服务!"+ex.ToString());
           }
       }

//事件:安装服务
       private void button3_Click(object sender, EventArgs e)
       {
           try
           {
               if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
               this.InstallService(serviceFilePath);
               MessageBox.Show("安装服务完成");
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }

}
       /// <summary>
       ///事件:卸载服务
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
       private void button4_Click(object sender, EventArgs e)
       {
           try
           {
               if (this.IsServiceExisted(serviceName))
               {
                   this.ServiceStop(serviceName);
                   this.UninstallService(serviceFilePath);
                   MessageBox.Show("卸载服务完成");
               }
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }

}

//事件:启动服务
       private void button5_Click(object sender, EventArgs e)
       {
           try
           {
               if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
               MessageBox.Show("启动服务完成");
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.ToString());
           }

}

//判断服务是否存在
       private bool IsServiceExisted(string serviceName)
       {
           ServiceController[] services = ServiceController.GetServices();
           foreach (ServiceController sc in services)
           {
               if (sc.ServiceName.ToLower() == serviceName.ToLower())
               {
                   return true;
               }
           }
           return false;
       }

//安装服务
       private void InstallService(string serviceFilePath)
       {
           using (AssemblyInstaller installer = new AssemblyInstaller())
           {
               installer.UseNewContext = true;
               installer.Path = serviceFilePath;
               IDictionary savedState = new Hashtable();
               installer.Install(savedState);
               installer.Commit(savedState);
           }
       }

//卸载服务
       private void UninstallService(string serviceFilePath)
       {
           using (AssemblyInstaller installer = new AssemblyInstaller())
           {
               installer.UseNewContext = true;
               installer.Path = serviceFilePath;
               installer.Uninstall(null);
           }
       }

//启动服务
       private void ServiceStart(string serviceName)
       {
           using (ServiceController control = new ServiceController(serviceName))
           {
               if (control.Status == ServiceControllerStatus.Stopped)
               {
                   control.Start();
               }
           }
       }

//停止服务
       private void ServiceStop(string serviceName)
       {
           using (ServiceController control = new ServiceController(serviceName))
           {
               if (control.Status == ServiceControllerStatus.Running)
               {
                   control.Stop();
               }
           }
       }
   }

10.为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows窗体,如下图所示:

利用C#编写一个Windows服务程序的方法详解

利用C#编写一个Windows服务程序的方法详解

11.由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目&ldquo;WindowsServiceClient&rdquo;,在弹出的上下文菜单中选择&ldquo;添加&rdquo;->&ldquo;新建项&rdquo;,在弹出的选择窗体中选择&ldquo;应用程序清单文件&rdquo;并单击确定,如下图所示:

利用C#编写一个Windows服务程序的方法详解

打开该文件,并将改为,如下图所示:

利用C#编写一个Windows服务程序的方法详解

12.IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开

利用C#编写一个Windows服务程序的方法详解

13.效果图

单击安装服务

利用C#编写一个Windows服务程序的方法详解

找到服务,可以查看到。

利用C#编写一个Windows服务程序的方法详解

卸载服务

利用C#编写一个Windows服务程序的方法详解

服务卸载成功,找不到服务。

利用C#编写一个Windows服务程序的方法详解

来源:https://blog.csdn.net/zkjd111/article/details/119968752

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com