Avatar of rmillersr
rmillersr

asked on 

Loading dynamic dll modules at run time with vb.net

I am working on a main application that will load dll files dynamically when put in a modules folder, i have the code working to some extent however if the name of the dll is changed then the code breaks.  Can anyone help me fix this and possibly show some examples of how to run different functions in the dll without programming the function names in the loader application.

using this question and answer i was able to get this far: https://www.experts-exchange.com/questions/23130718/Import-DLL-at-run-time-in-VB-NET.html

My code is attached below
Imports System.IO.File
Imports System.IO.Directory
Imports System.Reflection
Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call load_modules()
    End Sub
 
    Sub load_modules()
 
 
        Try
            Dim modules As Array = get_modules()
            Dim Assemblypath As String = modules(0)
            Dim A As Assembly = Assembly.LoadFrom(Assemblypath)
            Dim test As String = Strings.Right(Strings.Left(modules(0), modules(0).length - 4), modules(0).length - 14)
            Dim plugin As Object = A.CreateInstance(test & ".Mainclass", 1)
            Dim T As Type = plugin.GetType
            Dim MI As MethodInfo = T.GetMethod("Main", BindingFlags.Public Or BindingFlags.Instance)
            Dim ret = MI.Invoke(plugin, New Object() {1})
            Me.Controls.Add(ret)
        Catch ex As Exception
            If ex.Message = "Object reference not set to an instance of an object." Then
                MsgBox("Class name not MainClass or main function not named 'Main' please correct the module and reinstall")
                End
            End If
        End Try
    End Sub
    Function get_modules() As Array
        Try
            Dim filearray As Array = GetFiles(".\modules\", "*.dll", IO.SearchOption.AllDirectories)
            Dim arraysize As Integer = GetFiles(".\modules\", "*.dll", IO.SearchOption.AllDirectories).Length
            If filearray.Length > 0 Then
                Return filearray
            Else
                MsgBox("No modules to load, Application will now exit.")
                End
            End If
        Catch ex As Exception
            'If ex.InnerException = "Could not find a part of the path" Then
            'CreateDirectory(".\modules\")
            'MsgBox("Directory missing. Directory has been created, please add modules and try again.")
            'End
            'End If
        End Try
    End Function
End Class

Open in new window

.NET Programming

Avatar of undefined
Last Comment
rmillersr

8/22/2022 - Mon