Created
November 3, 2016 05:01
Self-installed windows service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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