Accueil > > > WINDOWS SERVICE MANAGER
WINDOWS SERVICE MANAGER
Information sur la source
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
Historique
- 29 août 2009 17:57:04 :
- corrections de fautes
Sources du même auteur
Sources de la même categorie
Commentaires et avis
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
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Forum
LINQLINQ par okosa
Cliquez pour lire la suite par okosa
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|