Service Program Install
1. Structure the Main() function of your service like this:
static void Main(string[] args)
{
if (args.Length == 0) {
// Run your service normally.
ServiceBase[] ServicesToRun = new ServiceBase[] {new YourService()};
ServiceBase.Run(ServicesToRun);
} else if (args.Length == 1) {
switch (args[0]) {
case "-install":
InstallService();
StartService();
break;
case "-uninstall":
StopService();
UninstallService();
break;
default:
throw new NotImplementedException();
}
}
}
2. Here is the supporting code:
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
private static bool IsInstalled()
{
using (ServiceController controller =
new ServiceController("YourServiceName")) {
try {
ServiceControllerStatus status = controller.Status;
} catch {
return false;
}
return true;
}
}
private static bool IsRunning()
{
using (ServiceController controller =
new ServiceController("YourServiceName")) {
if (!IsInstalled()) return false;
return (controller.Status == ServiceControllerStatus.Running);
}
}
private static AssemblyInstaller GetInstaller()
{
AssemblyInstaller installer = new AssemblyInstaller(
typeof(YourServiceType).Assembly, null);
installer.UseNewContext = true;
return installer;
}
3. Continuing with the supporting code..
private static void InstallService()
{
if (IsInstalled()) return;
try {
using (AssemblyInstaller installer = GetInstaller()) {
IDictionary state = new Hashtable();
try {
installer.Install(state);
installer.Commit(state);
} catch {
try {
installer.Rollback(state);
} catch { }
throw;
}
}
} catch {
throw;
}
}
private static void UninstallService()
{
if ( !IsInstalled() ) return;
try {
using ( AssemblyInstaller installer = GetInstaller() ) {
IDictionary state = new Hashtable();
try {
installer.Uninstall( state );
} catch {
throw;
}
}
} catch {
throw;
}
}
private static void StartService()
{
if ( !IsInstalled() ) return;
using (ServiceController controller =
new ServiceController("YourServiceName")) {
try {
if ( controller.Status != ServiceControllerStatus.Running ) {
controller.Start();
controller.WaitForStatus( ServiceControllerStatus.Running,
TimeSpan.FromSeconds( 10 ) );
}
} catch {
throw;
}
}
}
private static void StopService()
{
if ( !IsInstalled() ) return;
using ( ServiceController controller =
new ServiceController("YourServiceName")) {
try {
if ( controller.Status != ServiceControllerStatus.Stopped ) {
controller.Stop();
controller.WaitForStatus( ServiceControllerStatus.Stopped,
TimeSpan.FromSeconds( 10 ) );
}
} catch {
throw;
}
}
}
'Program > C#' 카테고리의 다른 글
[.Net] Windows 서비스 응용 프로그램 배포하기 (0) | 2020.05.10 |
---|---|
VisualStudio installer Uninstall 추가하기 (0) | 2020.05.10 |
특수문자 제거 정규식 (0) | 2018.06.21 |
FileSystemWatcher (폴더 모니터링 기능) (0) | 2018.06.21 |
크로스 스레드 문제 해결....CheckForIllegalCrossThreadCalls!! (0) | 2018.06.11 |