.NET => COM Invalid Cast Exception

      Comments Off on .NET => COM Invalid Cast Exception

If you get an InvalidCastException when accessing a COM object from .NET, it generally means that there is a version mismatch between the .NET interop dll and the COM object.

  1. Use Lutz Net Reflector to open the interop dll and disassemble the definition of the interface that you are trying to cast to. Note the interface ID (GUID).
  2. Use OLE Viewer to open the COM dll as a type library. Examine the interface definition to make sure the GUID is the same.
  3. If using DCOM/COM+, run Component Manager, open the component, open the interface list, right-click on the interface and select Properties. Once again the GUID should match.

If everything checks out, make sure that the COM interface is actually registered on your machine. Using an unregistered interface produces the same error message as using the wrong version. Note that if you are using DCOM remoting you do not need to have the component dll registered on the client machine, but you must register the dll that defines the interface that you are using. Just having the interop is not enough.

This is fairly obvious stuff once you figure it out, but it just took me several hours to track it down.