C# - Call a method in an external DLL using the name

By , 8/19/2012
(1 ratings)
The snippet uses reflection to call a method using the DLL filename, class name and name of the method and hand over an ArrayList of parameters.

Parameters:
nameOfDLL -> Full path and name of the DLL (has to be IL code (C++, C#, VB.NET))
nameOfClass -> Full name of the class including namespace
nameOfMethod -> The name of the method ;-)
parameters -> Any array list to hand over an unspecified amount of parameters.


Author: Rüdiger Vossel, translation by Michael List
using System.Reflection;
using System.Collections;

/// <summary>
/// Calls a method of a class of a external DLL and returns an error message (if an error occurs)
/// </summary>
public static String externalDLL(String nameOfDLL, String nameOfClass, String nameOfMethod, ArrayList parameters)
{
    String errorMessage = "";
    try
    {
        // First load the DLL
        Assembly assembly = Assembly.LoadFile(nameOfDLL);
        // Create a object with the given class name
        Object o = assembly.CreateInstance(nameOfClass);
        if (o != null)
        {
            // Parameter description
            Type[] typeArray = new Type[1];
            typeArray.SetValue(typeof(ArrayList), 0); // A parameter with type object at index 0

            // Get method
            MethodInfo mi = o.GetType().GetMethod(nameOfMethod, typeArray); // Get method info
            if (mi != null)
            {
                // Let's start ...
                errorMessage = (String)mi.Invoke(o, new Object[] { (ArrayList)parameters }); // Execute method with parameters
            }
            else
            {
                errorMessage = "Method <" + nameOfMethod + "> not found in class."; // Error .. 
            }
        }
        else
        {
            errorMessage = "Class <" + nameOfClass + "> not found in external plugin."; // Error .. 
        }
    }
    catch (System.IO.FileNotFoundException)
    {
        errorMessage = "External plugin <" + nameOfDLL + "> could not be loaded!";
    }
    return errorMessage;
}
Tagged with reflection, DLL, name, external, call.

Comments

 

Log in, to comment!