Search This Blog

Monday 31 October 2016

Kill process in c#

        using System.Diagnostics;
        using System.Collections;

        Hashtable hashtable;

        protected void Button1_Click(object sender, EventArgs e)
        {
            // Get already running process ids before running the Export to Excel method
            GetExcelProcesses();

            //Export to Excel Method
            ExportToExcel();

            // Kill the right process after Export to Excel completed
            KillExcel();
        }


        private void ExportToExcel()
        {
            // your export process is here...
        }


        private void GetExcelProcesses()
        {
            hashtable = new Hashtable();

            Process[] process = Process.GetProcessesByName("excel");
  
            int count = 0;

            foreach (Process ExcelProcess in process)
            {
                hashtable.Add(ExcelProcess.Id, count);
                count++;
            }
        }

        private void KillExcel()
        {
            Process[] process = Process.GetProcessesByName("excel");

            // check to kill the right process
            foreach (Process ExcelProcess in process)
            {
                if (hashtable.ContainsKey(ExcelProcess.Id) == false)
                {
                    ExcelProcess.Kill();
                }
            }

            process = null;
        }

No comments:

Post a Comment