Search code examples
.netvb.netcom.net-4.0late-binding

How create variables of types in COM object using late binding?


This is probably a noob question but seems that despite checking 15+ resources I'm still missing one thing in working with COM interfaces in .NET.

I'd like to unzip a file using Windows Shell. (My goals: works with Windows XP and higher, no 3rd party Zip libraries, no .DLL coming along with my exe, .) Simply instantiate Shell.Application COM object and call its methods. (Minimalistic approach.)

I can handle it using early binding (source, builds OK):

Dim sc As New Shell32.ShellClass()
Dim SrcFlder As Shell32.Folder = sc.NameSpace(sourceFilename)
Dim DestFlder As Shell32.Folder = sc.NameSpace(destinationDirName)
Dim Items As Shell32.FolderItems = SrcFlder.Items()
DestFlder.CopyHere(Items, 16) '16 = Respond with "Yes to All"

I can also handle it using late binding in , where I'm experienced. But I'm not sure how to use late binding in when it comes to types inside the COM module. First two lines of the following converted code work, but how to create variable of type Shell32.folder? It is not a public type (registered in Windows Registry) like Shell.Application is.

Dim st As Type = Type.GetTypeFromProgID("Shell.Application", True)
Dim sc As Object = Activator.CreateInstance(st, True)

'how to instantiate the following 'Shell32.Folder' and 'Shell32.FolderItems' types?
'Dim SrcFlder As Shell32.Folder = sc.NameSpace("d:\test.zip")
'Dim DestFlder As Shell32.Folder = sc.NameSpace("d:\test")
'Dim Items As Shell32.FolderItems = SrcFlder.Items()

'this will be called probably through the reflection, correct?
'DestFlder.CopyHere(Items, 16)  '16 = Respond with "Yes to All"

Reagrding this example: I'm not primarily asking about unzipping (although I need it), but I'd like to correctly work with COM objects in .NET using late binding (not only using early binding).


Solution

  • You need to use CreateObject and define each object as just Object

    Example (untested):

    Dim sc As Object = CreateObject("Shell32.ShellClass")
    Dim SrcFlder As Object = sc.NameSpace(sourceFilename)
    Dim DestFlder As Object = sc.NameSpace(destinationDirName)
    Dim Items As Object= SrcFlder.Items()
    DestFlder.CopyHere(Items, 16) '16 = Respond with "Yes to All"
    

    Note that this won't compile with Option Strict On

    However I will say that you should try and do early binding wherever possible.