System.InvalidCastException : Unable to cast object of type System.__ComObject to type Excel;

  • Thread starter Thread starter AnnabelleTrinh
  • Start date Start date
A

AnnabelleTrinh

Guest
Hello,

I have a very simple code.

var excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Open("Path");
Excel.Worksheet ws = wb.Worksheets["HeaderName"];
excelApp.Visible = true;
excelApp.UserControl = false;
ws.get_Range("A1").Value2 = "John";
wb.Close(true);

This code is run several times successively in a panel of unit test, and occasionally this Exception will be thrown :

---------------------------------------------------------

Result Message: System.InvalidCastException : Unable to cast object of type 'System.__ComObject' to type 'Microsoft.Office.Interop.Excel.ApplicationClass'.

Result StackTrace:
at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at Program.MyProgramTest.MethodTest()
-------------------------------------------------------------------------

It's a really random bug: if I rerun the MethodTest() that threw the exception, it will run with success.

It seems like this random exception occurring is a known bug but it doesn't seem to be fixed yet.

Thanks in advance for your answers

Continue reading...
 
Back
Top