C# 建立Windows服務demo

1、準備工做

1.操做系統:Windows 10 X64編程

2.開發環境:VS2017windows

3.編程語言:C#編程語言

4. .NET版本:.NET Framework 4.5編輯器

2、建立Windows Service

1.新建一個Windows Service,並將項目名稱改成「MyWinsService」,程序保存路徑本身選一個,以下圖所示:ide

二、在解決方案資源管理器內將Service1.cs改成MyService1.cs後,右鍵「查看代碼」圖標按鈕進入代碼編輯器界面,下面直接貼代碼:ui

     string filePath = $"{Application.StartupPath}\\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 + " " + "中止服務!");
            }
        }

3.雙擊項目「MyWindowsService」進入「MyService」設計界面,在空白位置右擊鼠標彈出上下文菜單,選中「添加安裝程序」,以下圖所示:spa

 四、進入頁面以後就會看到serviceProcessInstaller1和serviceInstaller1;操作系統

點擊「serviceProcessInstaller1」,在「屬性」窗體將Account改成LocalSystem(服務屬性系統級別),以下圖所示:設計

5.點擊「serviceInstaller1」,在「屬性」窗體將ServiceName改成MyService,Description改成個人服務,StartType保持爲Manual,以下圖所示:調試

 

6.鼠標右鍵點擊項目「MyWinsService」,在彈出的上下文菜單中選擇「生成」按鈕,生成咱們本身的windows服務了。

3、建立安裝、啓動、中止、卸載服務的Windows窗體

1.咱們以winform爲例子吧,建一個簡單的界面,這裏命名爲ServiveMan,修改屬性text爲windows服務管理,拖入四個Button,分別命名爲安裝、啓動、中止、卸載

2.整理了一個Windows服務管理的類,這裏我採用的是單例模式,若是有不理解的,我下一篇文章就分享一下單例模式。

    /// <summary>
    /// Windows服務管理
    /// </summary>
    public class serviceManager
    {
        private static serviceManager mSingle = null;
     //
public static serviceManager GetInstance() { if (mSingle == null) mSingle = new serviceManager(); return mSingle; }     //判斷服務是否存在 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(); } } }   }

3.接下來貼,windows服務管理類的使用方法,直接看代碼,代碼上都有註釋

  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";
        string serviceName = "MyService";
        
        /// <summary>
        /// 事件:安裝服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //判斷是否存在服務 - 存在則開啓服務
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                try
                {
                    serviceManager.GetInstance().ServiceStart(serviceName); //啓動服務              
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            serviceManager.GetInstance().InstallService(serviceFilePath);//不然安裝服務
        }

        /// <summary>
        /// 事件:啓動Windows服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //啓動Windows服務前判斷是否存在Windows服務
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                try
                {
                    serviceManager.GetInstance().ServiceStart(serviceName);//開啓Windows服務                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else
            {
                //服務未安裝
                DialogResult dr = MessageBox.Show("該服務還沒有安裝,是否安裝服務?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    serviceManager.GetInstance().InstallService(serviceFilePath);//安裝服務
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 事件:中止Windows服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                try
                {                
                    serviceManager.GetInstance().ServiceStop(serviceName);//中止Windows服務
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 事件:卸載Windows服務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (serviceManager.GetInstance().IsServiceExisted(serviceName))
            {
                serviceManager.GetInstance().ServiceStop(serviceName);//中止Windows服務
                serviceManager.GetInstance().UninstallService(serviceFilePath);//卸載Windows服務
            }
        }       
  }

四、爲了後續調試服務及安裝卸載服務的須要,將已生成的MyWinsService.exe引用到本Windows窗體,右鍵添加引用,選擇項目添加就能夠了。這裏就不上圖了。

5.   安裝服務,須要使用UAC中Administrator的權限,鼠標右擊項目,在彈出的上下文菜單中選擇「添加」->「新建項」,在彈出的選擇窗體中選擇「應用程序清單文件」並單擊肯定,以下圖所示:

 

 5.打開該文件,並將<requestedExecutionLevel level="asInvoker" uiAccess="false" />改成<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />,以下圖所示:

 

6.整個過程完成了,如今咱們能夠啓動項目了,啓動後可能會彈出以下所示的窗體(有的系統因UAC配置有可能不顯示),須要用管理員權限打開:

7.重啓項目以後就能夠了。

八、使用WIN+R的方式打開運行窗體,並在窗體內輸入services.msc後打開服務,就能夠看到下圖:

9.咱們能夠經過剛剛寫的開啓服務來打開服務,若是服務不用了能夠經過按鈕直接中止或者卸載。

ok,今天關於windows服務的demo就分享到這了,若是有疑問的能夠留言,講的不對的歡迎指出!!!

相關文章
相關標籤/搜索