Calling Shell32.dll from .NET Windows Service

Richard Scheffrin picture Richard Scheffrin · Jan 27, 2013 · Viewed 7.5k times · Source

I have a .NET 4.0 library that uses Shell32 and Folder.GetDetailsOf() to get metadata from WTV files. I have used it successfully with Console and Windows Forms apps without issue. But for some reason, when calling the component from a .NET 4.0 Windows Service, the call to initiate the Shell class causes a COM error.

The code that fails inside the library:

Shell32.Shell shell = new Shell();

The error:

Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{286E6F1B-7113-4355-9562-96B7E9D64C54}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

I read my fill of Apartment Threading, COM Interops, Dynamic, PIA's, etc, etc, etc :) But no combination of solutions I've found has solved the problem. It must be a calling from another thread that can't see the Interop. Help, please :)

Answer

Leandro picture Leandro · Jul 26, 2014

I had the same problem just recently with a command line application (console). Turns out, it was required to annotate the program's Main() method with the [STAThread] attribute. It has also been noted that it fails miserably in the exact same way if the entry point is annotated with [MTAThread] instead. I hope it helps.