begin process at 2012 05 27 02:01:09
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

.NET

 > WINDOWS SERVICE MANAGER

WINDOWS SERVICE MANAGER


 Information sur la source

Note :
Aucune note
Catégorie :.NET Source .NET ( DotNet ) Classé sous :installutil, ServiceController, serviceinstaller Niveau :Initié Date de création :16/08/2009 Date de mise à jour :29/08/2009 17:57:01 Vu / téléchargé :4 895 / 290

Auteur : fredzool

Ecrire un message privé
Site perso
Commentaire sur cette source (0)
Ajouter un commentaire et/ou une note

 Description

installer un service windows
desinstaller un service windows
demarrer un service windows
arreter un service windows

install windows services

installutil.exe

Source

  • namespace ServiceManager
  • {
  • using System.ServiceProcess;
  • using System.Diagnostics;
  • using System.IO;
  • using System.Text;
  • using System;
  • public class ManageServices
  • {
  • public ManageServices()
  • {
  • }
  • public bool InstallService(string servicePath, string serviceName)
  • {
  • //on cree les .bat pour installer et desinstaller le service
  • CreateBatFile(servicePath);
  • //si le service existe deja il faut d abord l arreter
  • bool serviceExists = false;
  • StopService(serviceName, out serviceExists);
  • //si le service existe on le desinstall
  • if (serviceExists)
  • {
  • InstallServiceWithBat(Directory.GetCurrentDirectory(), @"uninstall.bat");
  • System.Threading.Thread.Sleep(1500);
  • }
  • //on installe le service
  • InstallServiceWithBat(Directory.GetCurrentDirectory(), @"install.bat");
  • System.Threading.Thread.Sleep(1500);
  • //on demarre le service
  • StartService(serviceName);
  • File.Delete(Directory.GetCurrentDirectory() + @"\install.bat");
  • File.Delete(Directory.GetCurrentDirectory() + @"\uninstall.bat");
  • return true;
  • }
  • public bool StopService(string serviceName, out bool serviceExists)
  • {
  • ServiceController[] scServices;
  • scServices = ServiceController.GetServices();
  • serviceExists = false;
  • foreach (ServiceController scTemp in scServices)
  • {
  • if (scTemp.ServiceName.Equals(serviceName, StringComparison.CurrentCultureIgnoreCase))
  • {
  • serviceExists = true;
  • try
  • {
  • if (scTemp.Status != ServiceControllerStatus.Stopped)
  • {
  • scTemp.Stop();
  • scTemp.WaitForStatus(ServiceControllerStatus.Stopped);
  • }
  • return true;
  • }
  • catch (Exception ex)
  • {
  • throw new Exception("error while stopping the service " + serviceName);
  • }
  • }
  • }
  • return false;
  • }
  • public bool StartService(string serviceName)
  • {
  • ServiceController[] scServices;
  • scServices = ServiceController.GetServices();
  • foreach (ServiceController scTemp in scServices)
  • {
  • if (scTemp.ServiceName.Equals(serviceName, StringComparison.CurrentCultureIgnoreCase))
  • {
  • try
  • {
  • if (scTemp.Status != ServiceControllerStatus.Running)
  • scTemp.Start();
  • scTemp.WaitForStatus(ServiceControllerStatus.Running);
  • return true;
  • }
  • catch (Exception ex)
  • {
  • throw new Exception("error while startting the service " + serviceName);
  • }
  • }
  • }
  • return true;
  • }
  • private bool CreateBatFile(string servicePath)
  • {
  • //script d installation du service
  • StreamWriter sw = new StreamWriter(Directory.GetCurrentDirectory() + @"\install.bat");
  • string installutilPath = @"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\";
  • sw.Write(string.Format("{0}installutil.exe -i {1}", installutilPath, servicePath));
  • sw.Close();
  • //script de desinstallation du service
  • sw = new StreamWriter(Directory.GetCurrentDirectory() + @"\uninstall.bat");
  • sw.Write(string.Format("{0}installutil.exe -u {1}", installutilPath, servicePath));
  • sw.Close();
  • return true;
  • }
  • private bool InstallServiceWithBat(string targetDir, string bat)
  • {
  • Process p = null;
  • try
  • {
  • targetDir = string.Format(targetDir);
  • p = new Process();
  • p.StartInfo.WorkingDirectory = targetDir;
  • p.StartInfo.FileName = bat;
  • p.StartInfo.Arguments = string.Format("");
  • p.StartInfo.CreateNoWindow = false;
  • p.Start();
  • p.WaitForExit();
  • return true;
  • }
  • catch (Exception ex)
  • {
  • Console.WriteLine("Exception Occurred :{0},{1}",
  • ex.Message, ex.StackTrace.ToString());
  • return false;
  • }
  • }
  • }
  • }
namespace ServiceManager
{
    using System.ServiceProcess;
    using System.Diagnostics;
    using System.IO;
    using System.Text;
    using System;

    public class ManageServices
    {
        public ManageServices()
        {

        }

        public bool InstallService(string servicePath, string serviceName)
        {
            //on cree les .bat pour installer et desinstaller le service
            CreateBatFile(servicePath);

            //si le service existe deja il faut d abord l arreter
            bool serviceExists = false;
            StopService(serviceName, out serviceExists);

            //si le service existe on le desinstall
            if (serviceExists)
            {
                InstallServiceWithBat(Directory.GetCurrentDirectory(), @"uninstall.bat");
                System.Threading.Thread.Sleep(1500);
            }
            
            //on installe le service
            InstallServiceWithBat(Directory.GetCurrentDirectory(), @"install.bat");
            System.Threading.Thread.Sleep(1500);

            //on demarre le service
            StartService(serviceName);
            File.Delete(Directory.GetCurrentDirectory() + @"\install.bat");
            File.Delete(Directory.GetCurrentDirectory() + @"\uninstall.bat");
            return true;
        }

        public bool StopService(string serviceName, out bool serviceExists)
        {
            ServiceController[] scServices;
            scServices = ServiceController.GetServices();
            serviceExists = false;

            foreach (ServiceController scTemp in scServices)
            {
                if (scTemp.ServiceName.Equals(serviceName, StringComparison.CurrentCultureIgnoreCase))
                {
                    serviceExists = true;
                    try
                    {
                        if (scTemp.Status != ServiceControllerStatus.Stopped)
                        {
                            scTemp.Stop();
                            scTemp.WaitForStatus(ServiceControllerStatus.Stopped);
                        }

                        return true;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("error while stopping the service " + serviceName);
                    }
                }
            }
            return false;
        }


        public bool StartService(string serviceName)
        {

            ServiceController[] scServices;
            scServices = ServiceController.GetServices();

            foreach (ServiceController scTemp in scServices)
            {
                if (scTemp.ServiceName.Equals(serviceName, StringComparison.CurrentCultureIgnoreCase))
                {
                    try
                    {
                        if (scTemp.Status != ServiceControllerStatus.Running)
                            scTemp.Start();
                        scTemp.WaitForStatus(ServiceControllerStatus.Running);

                        return true;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("error while startting the service " + serviceName);
                    }
                }
            }

            return true;
        }

        private bool CreateBatFile(string servicePath)
        {
            //script d installation du service
            StreamWriter sw = new StreamWriter(Directory.GetCurrentDirectory() + @"\install.bat");
            string installutilPath = @"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\";
            sw.Write(string.Format("{0}installutil.exe -i {1}", installutilPath, servicePath));
            sw.Close();

            //script de desinstallation du service
            sw = new StreamWriter(Directory.GetCurrentDirectory() + @"\uninstall.bat");
            sw.Write(string.Format("{0}installutil.exe -u {1}", installutilPath, servicePath));
            sw.Close();

            return true;
        }


        private bool InstallServiceWithBat(string targetDir, string bat)
        {

            Process p = null;
            try
            {
                targetDir = string.Format(targetDir);
                p = new Process();
                p.StartInfo.WorkingDirectory = targetDir;
                p.StartInfo.FileName = bat;

                p.StartInfo.Arguments = string.Format("");
                p.StartInfo.CreateNoWindow = false;
                p.Start();
                p.WaitForExit();

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}",
                            ex.Message, ex.StackTrace.ToString());
                return false;
            }
        }
    }
}

 Conclusion

util si l on developpe une solution avec plusieurs services
ce petit utiltaire permet de mettre a jour les services selectionnees


donc pas besoin de lancer tous les services depuis visual studio
on gagne pas mal de temps

 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 Historique

29 août 2009 17:57:04 :
corrections de fautes

 Sources du même auteur

Source avec Zip Source avec une capture Source .NET (Dotnet) CASE GAME
Source avec Zip Source .NET (Dotnet) LOGICIEL DE FACTURATION ONGLET MYSQL IMPRESSION LISTVIE...
Source avec Zip Source .NET (Dotnet) JEU DE MEMOIRE SURCHARGE PICTUREBOX LECTURE ECRITURE ...
Source avec Zip Source .NET (Dotnet) TETRIS VERSION BETA

 Sources de la même categorie

Source avec Zip Source .NET (Dotnet) GESTION DES ASSURANCE DE CLIENTS par okosa
Source avec Zip Source .NET (Dotnet) CSHARP-WINDOWS-PHONE-7-- OPENSTACK NOVA CLIENT :: MADE BY "N... par jalel1234
Source .NET (Dotnet) CLASSE D'ENVOIE DE MAIL PAR SMTPCLIENT par wortmany
Source .NET (Dotnet) SÉRIALISATION (BINAIRE) OBJECT, IMAGE, CLASS ... par wortmany
Source avec Zip Source avec une capture Source .NET (Dotnet) ORIONBANQUE par toutphp

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture Source .NET (Dotnet) GESTIONNAIRE DE SERVICES par nseveno

Commentaires et avis

Aucun commentaire pour le moment.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

Executer un service a distance [ par cloud8716 ] Bonjour,Je suis debutant en C# et je dois faire un programme qui permet de lister, demarrer et arreter des services sur une machine distante.Pour ce q Gestion de services Windows distants [ par tigerskin ] Salut les codeurs J'ai un petit souci et je n'arrive pas à comprendre le problème. Je m'explique : j'utilise la classe ServiceController pour récupére


Nos sponsors


Sondage...

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 1,045 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales