How To Kill A Process

Do you need to kill (stop) a process running on Windows? I wrote the code below for my console apps .NET back utility and .NET file cleaner utility so if a user tries to start a second instance, it will automatically close.

You can kill any process with the second method, you just need the process name. If you don’t know the process name you can find it in the Windows Resource Monitor.

''' <summary>
''' Kills the current process.
''' </summary>
Public Sub KillProcess()
   KillProcess(Path.GetFileNameWithoutExtension(
               Assembly.GetEntryAssembly().Location))
End Sub

''' <summary>
''' Kills the process.
''' </summary>
''' <param name="processName">Name of the process.</param>
Public Sub KillProcess(processName As String)
   Contract.Requires(Of ArgumentNullException)(Not
                  String.IsNullOrEmpty(processName),
                  "processName is nothing or empty.")
   Dim app = System.Diagnostics.Process.GetProcessesByName(
               processName).FirstOrDefault

   If app IsNot Nothing Then
      app.Kill
      app.WaitForExit
   End If
End Sub