Guest User

Untitled

a guest
Dec 10th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. var ctl = ServiceController.GetServices().Where(s => s.ServiceName == "MyService").FirstOrDefault();
  2. if (ctl != null) {
  3. // now what?
  4. }
  5.  
  6. private static string GetExecutablePathForService(string serviceName, RegistryView registryView, bool throwErrorIfNonExisting)
  7. {
  8. string registryPath = @"SYSTEMCurrentControlSetServices" + serviceName;
  9. RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView).OpenSubKey(registryPath);
  10. if(key==null)
  11. {
  12. if (throwErrorIfNonExisting)
  13. throw new ArgumentException("Non-existent service: " + serviceName, "serviceName");
  14. else
  15. return null;
  16. }
  17. string value = key.GetValue("ImagePath").ToString();
  18. key.Close();
  19. if(value.StartsWith("""))
  20. {
  21. value = Regex.Match(value, ""([^"]+)"").Groups[1].Value;
  22. }
  23.  
  24. return Environment.ExpandEnvironmentVariables(value);
  25. }
  26.  
  27. var ctl = ServiceController
  28. .GetServices()
  29. .FirstOrDefault(s => s.ServiceName == "MyService");
  30. if (ctl != null) {
  31. // get version substring, you might have your own style.
  32. string substr = s.DisplayName.SubString("MyService".Length);
  33. Version installedVersion = new Version(substr);
  34. // do stuff, e.g. check if installed version is newer than current assembly.
  35. }
  36.  
  37. public static string ServiceVersion { get; private set; }
  38.  
  39. ServiceVersion = typeof(Program).Assembly.GetName().Version.ToString();
  40.  
  41. using System.Diagnostics;
  42. using System.ServiceProcess;
  43.  
  44. public partial class VaultServerUtilities : ServiceBase
  45. {
  46.  
  47. public static string ServiceVersion { get; private set; }
  48.  
  49. public VaultServerUtilities()
  50. {
  51. InitializeComponent();
  52.  
  53. VSUEventLog = new EventLog();
  54. if (!EventLog.SourceExists("Vault Server Utilities"))
  55. {
  56. EventLog.CreateEventSource("Vault Server Utilities", "Service Log");
  57. }
  58.  
  59. VSUEventLog.Source = "Vault Server Utilities";
  60. VSUEventLog.Log = "Service Log";
  61.  
  62. }
  63.  
  64.  
  65. protected override void OnStart(string[] args)
  66. {
  67.  
  68. ServiceVersion = typeof(Program).Assembly.GetName().Version.ToString();
  69. VSUEventLog.WriteEntry(string.Format("Vault Server Utilities v{0} has started successfully.", ServiceVersion));
  70.  
  71. }
  72.  
  73. protected override void OnStop()
  74. {
  75. VSUEventLog.WriteEntry(string.Format("Vault Server Utilities v{0} has be shutdown.", ServiceVersion));
  76. }
  77. }
Add Comment
Please, Sign In to add comment