Home > Net >  Killing the Excel Process c#
Killing the Excel Process c#

Time:01-25

In my web application, I have added an excel upload section.

Here When the user selects the excel file and clicked the upload button the below code is running.

If there was an error in upload it returns to the main page again and, when the user tried to upload the excel file again, it returns an error.

So I checked this by opening the task manager, and then I saw that the EXCEL process is running in the background. When I end the process of the excel file from there, then I can upload the excel file again.

So is there any way if the excel process is running kill that process and run the code without any error from the excel process. ?

This is the existing code.

if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx")) 
{
  string path = Server.MapPath("~/ExcelFile/"   excelFile.FileName);
  KillSpecificExcelFileProcess(excelFile.FileName);
  if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
  excelFile.SaveAs(path);
  ExcelPath = Server.MapPath("~/ExcelFile/")   path;
  Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
  Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
  Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
  Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
}

CodePudding user response:

Killing a process is like using a sledgehammer to drive in a panel pin. It'll work but what damage will it do in the process? when using iterop you need to use Try-Catch-Finally

try
{
    app = new Excel.Application();
    books = app.Workbooks;
    book = books.Add();
    sheets = book.Sheets;
    sheet = sheets.Add();
    range = sheet.Range["A1"];
    range.Value = "Lorem Ipsum";
    book.SaveAs(@"C:\Temp\ExcelBook"   
   DateTime.Now.Millisecond   ".xlsx");
    book.Close();
    app.Quit();
}
finally
{
    if (range != null) Marshal.ReleaseComObject(range);
    if (sheet != null) Marshal.ReleaseComObject(sheet);
    if (sheets != null) Marshal.ReleaseComObject(sheets);
    if (book != null) Marshal.ReleaseComObject(book);
    if (books != null) Marshal.ReleaseComObject(books);
    if (app != null) Marshal.ReleaseComObject(app);
}

This will make sure that the instance of excel that you created in code is disposed of should there be an error nd will be correctly closed when you are done with it.

  •  Tags:  
  • Related