Skip to content

Instantly share code, notes, and snippets.

@alexkuznetsov
Created November 3, 2016 05:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexkuznetsov/b4880005d73ce9decc93a1706394550a to your computer and use it in GitHub Desktop.
Save alexkuznetsov/b4880005d73ce9decc93a1706394550a to your computer and use it in GitHub Desktop.
Self-installed windows service
using System;
using System.Configuration.Install;
using System.Reflection;
using System.ServiceProcess;
namespace WinServiceHost
{
static class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
if (System.Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
case "--run":
startInConsole();
break;
default:
#if DEBUG
//Выполним только если присоединен отладчик
if (System.Diagnostics.Debugger.IsAttached)
{
startInConsole();
}
#endif
Console.WriteLine("Некорректное использование! Используйте следующие ключи:");
Console.WriteLine("--install - Установка службы");
Console.WriteLine("--uninstall - Удаление службы");
Console.WriteLine("--run - Запуск в консоли");
Console.WriteLine("пример использования: \r\n" + System.AppDomain.CurrentDomain.FriendlyName + " --параметр");
Console.ReadLine();
break;
}
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ApplicationServiceHost()
};
ServiceBase.Run(ServicesToRun);
}
}
private static void startInConsole()
{
var svc = new ApplicationServiceHost();
svc.Start(null);
Console.WriteLine("Сервис запущен в оконном режиме. Для выхода нажмите любую клавишу");
Console.ReadLine();
svc.Stop();
}
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is Exception)
{
var message = ((Exception)e.ExceptionObject).Message;
System.Diagnostics.Trace.TraceError("Error: {0}", message);
}
else
{
System.Diagnostics.Trace.TraceError("Error: {0}", e.ExceptionObject);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment