Search code examples
c#processwmi

C# WMI Process Restarter


Scenario

I have a bunch of processes running on a server as part of various C# Applications. Occasionally some of these crash for whatever reason (old legacy code that I don't currently have the time to replace or refactor).

Idea

I want to create a C# Service that continually checks to see if these processes are running, and if not, restart them.

Questions

Someone mentioned WMI? - And something about there being a C# wrapper for this? Something that essentially lets you write.

   Processes.GetProcessByName("MyProcess");

any help, advice, suggestions, would be greatly appreciated.

EDIT:

I've seen an example of something that restarts Services, and it uses WindowsIdentity to impersonate a user, logon to a server and restart the services....Something similar would be fantastic, although I'm not sure how to even go about implementing this.


Solution

  • using System.Diagnostics;
    using System.Linq;
    
    public static Process GetProcessByName(string processName)
    {  
        return Process
                 .GetProcesses()
                 .FirstOrDefault(p => p.ProcessName == processName);
    }
    

    Something like that?