欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用C#編寫一個Windows服務程序的方法詳解

 更新時間:2023年03月14日 08:34:25   作者:小惡魔@  
這篇文章主要為大家詳細介紹了如何利用C#編寫一個Windows服務程序,文中的實現(xiàn)方法講解詳細,具有一定的參考價值,感興趣的可以了解一下

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

2.輸入項目名稱,選擇安裝位置,,選擇安裝框架版本;創(chuàng)建。

3.找到MyService.cs ,右擊‘查看代碼’

添加如下代碼:

public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }
        string filePath = @"D:\MyServiceLog.txt";
        protected override void OnStart(string[] args)
        {//服務啟動時,執(zhí)行該方法
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服務啟動!");
            }
        }
        protected override void OnStop()
        {//服務關閉時,執(zhí)行該方法
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服務停止!");
            }
        }
    }

4.雙擊MyService.cs,在出現(xiàn)的界面中右擊–>選擇“添加安裝程序”。

點擊后,會自動生產(chǎn)連個控件,sericcelnstaller1 和sericeProcessInstaller1

5.分別設置兩個控件的屬性

右擊serviceInstaller1 點擊屬性

分別設置:服務安裝的描述,服務的名稱,啟動的類型 。

在serviceProcessInstaller1 ,設置Account(服務屬性系統(tǒng)級別),設置“本地服務”

6.找到項目,右擊“重新生成”。

7.在同一個解決方案下,添加Windows From項目應用窗體:

①點擊“添加”,新建項目,選擇Windows窗體應用。要注意添加時,選擇的路徑,是否在同一個解決方案目錄下。

8.找到Form設計窗體,添加控件如圖??丶ぞ呦湓诓藛螜?ndash;>視圖–>找到‘工具箱’。如圖所示

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;//是否使用系統(tǒng)外殼程序啟動進程
                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");//執(zhí)行關機命令
                myProcess.StandardInput.WriteLine("shutdown -r -t 60");//執(zhí)行重啟計算機命令
            }
            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.為了后續(xù)調(diào)試服務及安裝卸載服務的需要,將已生成的MyWindowsService.exe引用到本W(wǎng)indows窗體,如下圖所示:

11.由于需要安裝服務,故需要使用UAC中Administrator的權限,鼠標右擊項目“WindowsServiceClient”,在彈出的上下文菜單中選擇“添加”->“新建項”,在彈出的選擇窗體中選擇“應用程序清單文件”并單擊確定,如下圖所示:

打開該文件,并將改為,如下圖所示:

12.IDE啟動后,將會彈出如下所示的窗體(有的系統(tǒng)因UAC配置有可能不顯示),需要用管理員權限打開

13.效果圖

單擊安裝服務

找到服務,可以查看到。

卸載服務

服務卸載成功,找不到服務。

以上就是利用C#編寫一個Windows服務程序的方法詳解的詳細內(nèi)容,更多關于C# Windows服務程序的資料請關注腳本之家其它相關文章!

相關文章

  • C#實現(xiàn)身份證實名認證接口的示例代碼

    C#實現(xiàn)身份證實名認證接口的示例代碼

    身份證實名認證,即通過姓名和身份證號校驗個人信息的匹配程度,廣泛應用于金融、互聯(lián)網(wǎng)等多個領域,本文主要介紹了C#實現(xiàn)身份證實名認證接口的示例代碼,感興趣的可以了解一下
    2024-09-09
  • C#讀取命令行參數(shù)的方法

    C#讀取命令行參數(shù)的方法

    這篇文章主要介紹了C#讀取命令行參數(shù)的方法,可實現(xiàn)讀取程序輸入命令行的所有參數(shù),便于調(diào)試程序,比較簡單實用,需要的朋友可以參考下
    2015-04-04
  • C#聊天程序服務端與客戶端完整實例代碼

    C#聊天程序服務端與客戶端完整實例代碼

    這篇文章主要介紹了C#聊天程序服務端與客戶端完整實例代碼,很經(jīng)典的應用,需要的朋友可以參考下
    2014-07-07
  • C#實現(xiàn)簡單工廠模式

    C#實現(xiàn)簡單工廠模式

    這篇文章介紹了C#實現(xiàn)簡單工廠模式的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • C#獲取Excel文件所有文本數(shù)據(jù)內(nèi)容的示例代碼

    C#獲取Excel文件所有文本數(shù)據(jù)內(nèi)容的示例代碼

    獲取上傳的?EXCEL?文件的所有文本信息并存儲到數(shù)據(jù)庫里,可以進一步實現(xiàn)對文件內(nèi)容資料關鍵字查詢的全文檢索,有助于我們定位相關文檔,本文詳細介紹了C#獲取Excel文件所有文本數(shù)據(jù)內(nèi)容實現(xiàn)步驟和代碼,需要的朋友可以參考下
    2024-07-07
  • C#使用控制臺列出當前所有可用的打印機列表

    C#使用控制臺列出當前所有可用的打印機列表

    這篇文章主要介紹了C#使用控制臺列出當前所有可用的打印機列表,涉及C#操作計算機硬件的相關使用技巧,非常具有實用價值,需要的朋友可以參考下
    2015-04-04
  • C#構造函數(shù)在基類和父類中的執(zhí)行順序

    C#構造函數(shù)在基類和父類中的執(zhí)行順序

    這篇文章介紹了C#構造函數(shù)在基類和父類中的執(zhí)行順序,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-04-04
  • C#實現(xiàn)串口示波器

    C#實現(xiàn)串口示波器

    這篇文章主要為大家詳細介紹了C#實現(xiàn)串口示波器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • C#獲取并修改文件擴展名的方法

    C#獲取并修改文件擴展名的方法

    這篇文章主要介紹了C#獲取并修改文件擴展名的方法,實例分析了C#編程方式修改文件擴展名的技巧,涉及Path類的使用方法,需要的朋友可以參考下
    2015-04-04
  • C#和vb.net實現(xiàn)PDF 添加可視化和不可見數(shù)字簽名

    C#和vb.net實現(xiàn)PDF 添加可視化和不可見數(shù)字簽名

    本文通過C#程序代碼展示如何給PDF文檔添加可視化數(shù)字簽名和不可見數(shù)字簽名。文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08

最新評論