程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 創建window服務

C# 創建window服務

編輯:C#入門知識

using System; 
using System.Threading; 
using System.ServiceProcess; 
using System.Collections; 
using System.Configuration.Install; 
using System.Diagnostics; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Collections.Specialized; 
using System.IO; 
namespace WSGPSServices 

    public partial class myService : ServiceBase 
    { 
        #region 成員變量 
        public string strCurrPath = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).Directory.FullName; 
        public string servicesname = "WSGPSServices";//服務 
        public string Proceename = "WSGPSGateway.exe";// 進程 
        #endregion 
        protected override void Dispose(bool disposeing) 
        { 
            if (disposeing) 
            { 
                if (components != null) 
                { 
                    components.Dispose(); 
                } 
               Register(servicesname, strCurrPath); 
            } 
        } 
        #region 注冊卸載服務 
        //注冊服務 
        public void Register(string servicesname, string strServiceInstallPath) 
        { 
            IDictionary mySavedState = new Hashtable(); 
            try 
            { 
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(servicesname); 
                //服務已經存在則卸載   
                if (ServiceIsExisted(servicesname)) 
                { 
                    UnInstallService(servicesname, strCurrPath); 
                } 
                service.Refresh(); 
                //注冊服務   
                AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); 
                mySavedState.Clear(); 
                myAssemblyInstaller.Path = "WSGPSServices.exe"; 
                myAssemblyInstaller.UseNewContext = true; 
                myAssemblyInstaller.Install(mySavedState); 
                myAssemblyInstaller.Commit(mySavedState); 
                myAssemblyInstaller.Dispose(); 
                service.Start(); 
                ProcessStartInfo startinfo = new ProcessStartInfo("WSGPSGateway.exe"); 
                startinfo.WindowStyle = ProcessWindowStyle.Hidden; 
                startinfo.Arguments = Application.StartupPath + "//WSGPSGateway.exe"; 
                Process.Start(startinfo); 
                InitializeComponent(); 
            } 
            catch (Exception ex) 
            { 
                throw new Exception("注冊服務時出錯:" + ex.Message); 
            } 
        } 
        //卸載服務 
        public void UnInstallService(string strServiceName, string strServiceInstallPath) 
        { 
            try 
            { 
                if (ServiceIsExisted(servicesname)) 
                { 
                    AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); 
                    myAssemblyInstaller.UseNewContext = true; 
                    myAssemblyInstaller.Path = "WSGPSServices.exe"; 
                    myAssemblyInstaller.Uninstall(null); 
                    myAssemblyInstaller.Dispose(); 
                    KillProcess(); 
                } 
            } 
            catch (Exception ex) 
            { 
                throw new Exception("卸載服務時出錯:" + ex.Message); 
            } 
        } 
        //卸載服務時結束進程 
        private void KillProcess() 
        { 
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();//得到所有打開的進程      
            try 
            { 
                foreach (Process thisproc in Process.GetProcessesByName(Proceename)) 
                { 
                    if (!thisproc.CloseMainWindow()) 
                    { 
                        thisproc.Kill(); 
                    } 
                } 
            } 
            catch (Exception Exc) 
            { 
                throw Exc; 
            } 
        } 
        #endregion 
        #region 啟動服務與應用程序 
        //啟動服務(啟動存在的服務,30秒後啟動失敗報錯)   
        public void StartService(string serviceName) 
        { 
            if (ServiceIsExisted(servicesname)) 
            { 
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("WSGPSServices"); 
                if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) 
                { 
                    service.Start(); 
                    for (int i = 0; i < 30; i++) 
                    { 
                        service.Refresh(); 
                        System.Threading.Thread.Sleep(1000); 
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) 
                        { 
                            ProcessStartInfo startinfo = new ProcessStartInfo("WSGPSGateway.exe"); 
                            startinfo.WindowStyle = ProcessWindowStyle.Hidden; 
                            startinfo.Arguments = Application.StartupPath + "//WSGPSGateway.exe"; 
                            Process.Start(startinfo); 
                            break; 
                        } 
                        if (i == 29) 
                        { 
                            throw new Exception("服務WSGPS Services啟動失敗!"); 
                        } 
                    } 
                } 
            } 
        } 
        //判斷服務是否存在   
        public bool ServiceIsExisted(string serviceName) 
        { 
            ServiceController[] services = ServiceController.GetServices(); 
            foreach (ServiceController s in services) 
            { 
                if (s.ServiceName == servicesname) 
                { 
                    return true; 
                } 
            } 
            return false; 
        } 
        #endregion 
        #region Timer定時任務與構造方法 
        //Timer構造方法 
        private void InitializeComponent() 
        { 
            this.components = new System.ComponentModel.Container(); 
            this.Timers = new System.Windows.Forms.Timer(this.components); 
            this.Timers.Enabled = true; 
            this.Timers.Interval = 180000; 
            this.Timers.Tick += new System.EventHandler(this.Timers_Tick); 
        } 
        //Timer定時檢查任務 
        private void Timers_Tick(object sender, EventArgs e) 
        { 
            ServiceController[] services = ServiceController.GetServices(); 
            foreach (ServiceController s in services) 
            { 
                if (s.ServiceName == servicesname) 
                { 
                    return;//存在返回空 
                } 
                else 
                { 
                    Register(servicesname, strCurrPath);//無當前服務則重新注冊服務 
                } 
            } 
        } 
        #endregion 
    } 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved