C# + WMI – Check Status of Windows Services in Remote Computer

C# + WMI – Check Status of Windows Services in Remote Computer

   WindowsService.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Management;
 
   namespace NetworkMonitor
   {
      public class WindowsService
      {
         private string HostName;
         private Notification notify;
         private Library lib;
 
         public WindowsService(string HostName)
         {
            this.HostName = HostName;
            this.notify = new Notification();
 
            this.lib = new Library();
         }
 
         public void WindowsServiceValidate(string loginname, string password)
         {
            try
            {
 
               ConnectionOptions op = new ConnectionOptions();
 
               op.Username = loginname;
               op.Password = password;
               op.EnablePrivileges = true;
               op.Impersonation = ImpersonationLevel.Impersonate;
 
               ManagementScope scope;
 
               if (this.lib.IsLocalNetwork(this.HostName))
                  scope = new ManagementScope(@"\\" + this.HostName + @"\root\cimv2");
               else
                  scope = new ManagementScope(@"\\" + this.HostName + @"\root\cimv2", op);
 
               scope.Connect();
 
               ManagementPath path = new ManagementPath("Win32_Service");
               ManagementClass services = new ManagementClass(scope, path, null);
 
               foreach (ManagementObject service in services.GetInstances())
                  Console.WriteLine(service.GetPropertyValue("Name") + " " + service.GetPropertyValue("State"));
 
            }
            catch (Exception ex)
            {
               Console.WriteLine(ex.Message);
            }
         }
      }
   }
 
   Library.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Net;
 
   namespace NetworkMonitor
   {
      public class Library
      {
         public bool IsLocalNetwork(string HostName)
         {
            try
            {
               IPAddress[] hostIPs = Dns.GetHostAddresses(HostName);
               IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
 
               foreach (IPAddress hostIP in hostIPs)
               {
                  if (IPAddress.IsLoopback(hostIP)) return true;
 
                  foreach (IPAddress localIP in localIPs)
                  {
                     if (hostIP.Equals(localIP)) return true;
                  }
               }
            }
            catch (Exception ex) { }
 
            return false;
         }
      }
   }