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;
        }

Zip file in asp.net

Step 1:- Download 7-Zip from http://www.7-zip.org/download.html

Step 2:- Complete Code

using System.Diagnostics;

string SevenZipPath = @"C:\Program Files\7-Zip\7z.exe";
string FilePath = @"D:\Test\Files";

ProcessStartInfo processStartInfo = new ProcessStartInfo(SevenZipPath);
processStartInfo.Arguments = string.Format("a -t7z {0}.7z {0}", FilePath);
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(processStartInfo);

Step 3:-Explanation

Get the 7-Zip installed path
@"C:\Program Files\7-Zip\7z.exe"

Get the Files path  
@"D:\Test\Files"

Note:-

In this sample code file save in the Test folder with name Files.7z