How do I kill a process using Vb.NET or C#?

bugBurger picture bugBurger · Sep 22, 2008 · Viewed 162.2k times · Source

I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code.

Does any one have any straight-forward code for killing a process using vb.net or c#?

Answer

Blair Conrad picture Blair Conrad · Sep 22, 2008

You'll want to use the System.Diagnostics.Process.Kill method. You can obtain the process you want using System.Diagnostics.Proccess.GetProcessesByName.

Examples have already been posted here, but I found that the non-.exe version worked better, so something like:

foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
{
    try
    {
        p.Kill();
        p.WaitForExit(); // possibly with a timeout
    }
    catch ( Win32Exception winException )
    {
        // process was terminating or can't be terminated - deal with it
    }
    catch ( InvalidOperationException invalidException )
    {
        // process has already exited - might be able to let this one go
     }
}

You probably don't have to deal with NotSupportedException, which suggests that the process is remote.