Home > DeveloperSection > Articles > Kill a Process in C# with Example

Kill a Process in C# with Example


C# C# 
Ratings:
1 Comment(s)
 24013  View(s)
Rate this:

Kill a Process in C# with Example

Sometimes we want to terminate or kill a process, which are already running or previously created process. To kill the process in c sharp use System.Diagonistics name spaces and use named ‘Kill()’ method which is available in Process class.

Here I am giving an example to kill process. Let’s see the brief description on it.

Example:  Here I am creating a process and after 2 second killed it.

To kill the previously created process writes the following code.

using System.Diagnostics;

namespace ConsoleProcessTest

{

    class Program

    {

        static voidMain(string[] args)

        {

              // create the  process to launch another exe file

            Process myProcess= Process.Start(@"C:\Users\Sachindra\Desktop\Logic.exe");

 

            // take 2 second to kill the process

            Thread.Sleep(2000);

            // kill the process

            myProcess.Kill();

 

        }

      

    } 

  

}

After debug this code your Logic.exe executable file will execute and after 2 second it will close.

To kill already running process:

To kill already running process writes the following code.

using System.Diagnostics;

 

namespace AllreadyRunningProcess

{

    class Program

    {

        static voidMain(string[] args)

        {

            // Store all running process in the system

            Process[] runingProcess= Process.GetProcesses();

            for (inti=0; i<runingProcess.Length; i++)

            {

                // compare equivalent process by their name

                if(runingProcess[i].ProcessName=="mspaint")

                {

                    // kill  running process

                   runingProcess[i].Kill();

                }

     

            }

           

           

        }

    }

}

After debugging the code if ‘mspaint’ process is running then it will close.


good article

By aken H on   4 years ago

hi Arun,

  this is nice article.

thanks.


Don't want to miss updates? Please click the below button!

Follow MindStick