07 July, 2014

Write a Windows Service in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Configuration.Install;
using System.ComponentModel;
using System.Diagnostics;

namespace anyconnect_SBL
{
    class Program : ServiceBase
    {
        static void Main(string[] args)
        {
            ServiceBase.Run(new Program());
        }
        public Program()
        {
            this.ServiceName = "Anyconnect_SBL";
            Process myProcess = new Process();
            try
            {
                string dir = AppDomain.CurrentDomain.BaseDirectory;
                string parent = System.IO.Directory.GetParent(System.IO.Directory.GetParent(dir).FullName).FullName;
                myProcess.StartInfo.UseShellExecute = false;
                myProcess.StartInfo.FileName = parent + "\\vpncli.exe";
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
        }
        protected override void OnStop()
        {
            base.OnStop();
        }
    }  
        [RunInstaller(true)]
        public class MyWindowsServiceInstaller : Installer
        {
            public MyWindowsServiceInstaller()
            {
                var processInstaller = new ServiceProcessInstaller();
                var serviceInstaller = new ServiceInstaller();

                processInstaller.Account = ServiceAccount.LocalSystem;

                serviceInstaller.DisplayName = "My Service";
                serviceInstaller.StartType = ServiceStartMode.Manual;

                serviceInstaller.ServiceName = "Anyconnect_SBL";

                this.Installers.Add(processInstaller);
                this.Installers.Add(serviceInstaller);
            }
        }  
}

No comments:

Post a Comment