首页 > 系统相关 >C#创建Windows服务

C#创建Windows服务

时间:2022-09-26 10:59:05浏览次数:63  
标签:C# 创建 void System new Windows serviceName installer using

一、创建Windows Service

1、新建一个Windows Service,并将项目名称改为"MyWindowsService":

 

 

 2、在解决方案中将Service1.cs改为MyService.cs

 

 

 3、点击查看代码

using System;
using System.IO;
using System.ServiceProcess;

namespace MyWindowsService
{
    public partial class MyService : ServiceBase
    {
        string filePath = @"C:\Work\ServiceLog.txt";

        public MyService()
        {
            InitializeComponent();
        }

        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、双击项目“MyWindowsService”进入"MyService"设计界面,在空白位置右击鼠标弹出上下文菜单,选中"Add Installer"

 

 5、生成两个组件,分别是"serviceInstaller1"和"serviceProcessInstaller1"

 

 6、点击"serviceInstaller1",在"属性"窗体将ServiceName改为MyService,Description改为我的服务

 

 7、点击"serviceProcessInstaller1",在"属性"窗体将Account改为LocalSystem

 

 8、生成服务程序。

二、创建安装、启动、停止、卸载服务的窗体

1、在同一解决方案中新建一个Windows Form项目,命名为WindowsServiceClient

 

 2、将该项目设置为启动项目,并在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务

3、添加引用"System.Configuration.Install"及"System.ServiceProcess"

4、编辑代码

using System;
using System.Collections;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Configuration.Install;

namespace WindowsServiceClient
{
    public partial class Form1 : Form
    {
        string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";
        string serviceName = "MyService";

        public Form1()
        {
            InitializeComponent();
        }

        private void btnInstall_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceFilePath);
            this.InstallService(serviceFilePath);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
        }

        private void btnUninstall_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName))
            {
                this.ServiceStop(serviceName);
                this.UninstallService(serviceFilePath);
            }
        }

        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();
                }
            }
        }
    }
}

5、添加调试引用,

 

 6、由于需要安装服务,故需要使用UAC中Administrator的权限,在项目“WindowsServiceClient”添加“Application Manifest File”并单击确定

 

 7、编辑该文件,将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
             If you want to change the Windows User Account Control level replace the 
             requestedExecutionLevel node with one of the following.

        <requestedExecutionLevel  level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel  level="highestAvailable" uiAccess="false" />

            Specifying requestedExecutionLevel element will disable file and registry virtualization. 
            Remove this element if your application requires this virtualization for backwards
            compatibility.
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
      </requestedPrivileges>
    </security>
  </trustInfo>

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of the Windows versions that this application has been tested on and is
           is designed to work with. Uncomment the appropriate elements and Windows will 
           automatically selected the most compatible environment. -->

      <!-- Windows Vista -->
      <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->

      <!-- Windows 7 -->
      <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->

      <!-- Windows 8 -->
      <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->

      <!-- Windows 8.1 -->
      <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->

      <!-- Windows 10 -->
      <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->

    </application>
  </compatibility>

  <!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
       DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need 
       to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should 
       also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config. -->
  <!--
  <application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
      <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    </windowsSettings>
  </application>
  -->

  <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
  <!--
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
          type="win32"
          name="Microsoft.Windows.Common-Controls"
          version="6.0.0.0"
          processorArchitecture="*"
          publicKeyToken="6595b64144ccf1df"
          language="*"
        />
    </dependentAssembly>
  </dependency>
  -->

</assembly>

 

标签:C#,创建,void,System,new,Windows,serviceName,installer,using
From: https://www.cnblogs.com/cabinsummer/p/16730091.html

相关文章

  • #100daysofcode
    #100daysofcodeR1D9Photoby瓦列里·西索耶夫on不飞溅学习做了一些触摸打字课。这有助于输入大量代码以下来源文档中只能有一个body元素<body></body>......
  • kali下docker环境安装
    step1查看linux内核Docker需要Linux内核大于3.10并且是64位的,可以用uname-a可以查看是否符合要求uname-aLinuxkali5.18.0-kali5-amd64#1SMPPREEMPT_DYNAM......
  • HMS Core上新啦!
    HMSCore上新啦!分析服务营销分析报告全新上线;?ha_source=hms1运动健康服务支持目标场景事件订阅;音频编辑服务提供专业的三维声音频编辑与渲染能力,更多HMSCore能力可点击网......
  • Photoshop Elements 2023 for Mac(这样拍大合照更好看)
    PhotoshopElements2023是创建照片风格的最简单的软件,内含有多种模版,让您创造出令人难以置信的照片,使用自动生成的作品和智能编辑选项,将您最好的照片展示出来。拍摄大合......
  • rsync 同步日志到备份机器
    检查是否安装软件[root@test~]#rpm-qa|greprsyncrsync-3.1.2-10.el7.x86_64 服务器配置cat/etc/rsyncd.confuid=rootgid=rootusechroot=noma......
  • .netcore 下搭建本地nuget服务器
    1.首先创建一个普通的项目这个项目后面会放入我们自定义的nuget服务器给予其他项目应用2.我们对这个项目进行一下设置1)项目->属性选中构建nuget包2)项目点击发布......
  • vscode 打包报错 error code ELIFECYCLE error This is probably not a problem wi
    执行命令:npmrunbuild详细报错信息:0infoitworkedifitendswithok1verbosecli[1verbosecli'C:\\ProgramFiles(x86)\\nodejs\\node.exe',1verbose......
  • python学习(mooc北京理工大学课程)1-5章
    1.python基本语法元素1.1正式学习前的基础知识1.1.1计算机的概念计算机是根据指令操作数据的设备1)功能性对数据的操作,表现为数据计算、输入输出处理和结果存储等 2)......
  • redis curd 操作故障模拟
    1、下载对应的包,并编译gitclonehttps://gitlab.onemt.co/onemt-injection/redis-injection.gitmakebuild或者下载这个链接中的可执行文件 https://files.cnblogs......
  • 博客园背景css代码
    #google_ad_c1, #google_ad_c2 {display:none;}.syntaxhighlighter a, .syntaxhighlighter div, .syntaxhighlighter code, .syntaxhighlighter table, .synta......