Our robotics software has problems to interact with MS Excel, when the last session was killed. Ok, the problem ocures, when there are recovery files available and I could fix that problem, by deactivating autosave. UIPath - our robotics software, bases on .Net - does not always close the excel.application correctly after the interaction or better - I cannot guaranty, that there is not running excel task. The task may also be started by UIPath itself.
I want to write an activity, that surely closes all excel instances
without killing - p.Kill()
- them.
The function has no input and no output.
It looks like this:
public static class ExcelCleaner
{
private const string __EXCELAPP_REGKEY = "Excel.Application";
private const string __EXCEL_TASKNAME = "EXCEL";
static void Main(string[] args)
{
while (ExcelRunning())
{
Microsoft.Office.Interop.Excel.Application ExApp = null;
ExApp = System.Runtime.InteropServices.Marshal.GetActiveObject(__EXCELAPP_REGKEY) as Microsoft.Office.Interop.Excel.Application;
if (ExApp == null) { throw new System.NullReferenceException("Error - Unable to attach " + __EXCELAPP_REGKEY + " !"); }
foreach (Microsoft.Office.Interop.Excel.Workbook WB in ExApp.Workbooks)
{
WB.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
if (WB != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB); }
}
ExApp.Application.Quit();
if (ExApp.Application != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExApp.Application); }
try
{
ExApp.Quit();
}
catch{ }
finally {
if (ExApp != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExApp); }
}
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
}
private static bool ExcelRunning() { if (System.Diagnostics.Process.GetProcessesByName(__EXCEL_TASKNAME).Length > 0) { return true; } return false; }
}
Running one Excel task, that code closes excel correctly, but the task is still available and the While
loop is never escaped. A running Excel task is a bad situation for the next excel access of our robotics software.
The problem is, I do not know about Excel - Com-Objects
, that are referenced in UIPath, as the robotics software uses the Excel.Interop.Office.Excel
Com-Interface, but its a blackbox.