Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load a DLL from a specific folder?

Tags:

c#

assemblies

dll

At the moment, I have this code :

var shellViewLibrary = Assembly.LoadFrom(Path.Combine(_DllsPath, _DllShellView));
IEnumerable<Type> types = shellViewLibrary.GetTypes();

foreach (Type type in types)
{
    var typeIShellViewInterface = type.GetInterface(_NamespaceIShellView, false);
    if (typeIShellViewInterface != null)
    {
        //here
    }
}

The thing is that where I got //here I want to use Activator.CreateInstance to create an object whose type is type in a specific folder (that is outside the build folder) I tried about 20 different things, most of them with this : http://msdn.microsoft.com/en-us/library/d133hta4.aspx but none works... The typical thing I tried is :

object MyObj = Activator.CreateInstance(shellViewLibrary.FullName, type.FullName);

or

object MyObj = Activator.CreateInstance(Path.Combine(_DllsPath, _DllShellView), type.FullName);

I always got different exception, the most common being :

XamlParseException

I feel like that I'm not using Activator.CreateInstance in the right way with 2 parameters. What should I do ?

like image 760
Guillaume Slashy Avatar asked Dec 01 '22 06:12

Guillaume Slashy


1 Answers

This is an example of "Dynamically Loading a .dll from a Specific Folder" at runtime.

// Check if user has access to requested .dll.
string strDllPath = Path.GetFullPath(strSomePath);
if (File.Exists(strDllPath))
{
    // Execute the method from the requested .dll using reflection (System.Reflection).
    Assembly DLL = Assembly.LoadFrom(strDllPath);
    Type classType = DLL.GetType(String.Format("{0}.{1}", strNmSpaceNm, strClassNm));
    if (classType != null)
    {
        // Create class instance.
        classInst = Activator.CreateInstance(classType);

        // Invoke required method.
        MethodInfo methodInfo = classType.GetMethod(strMethodName);
        if (methodInfo != null)
        {
            object result = null;
            result = methodInfo.Invoke(classInst, new object[] { dllParams });
            return result.ToString();
        }
    }
}

This took me a while to work out so I hope it is of some use...

like image 85
MoonKnight Avatar answered Dec 09 '22 14:12

MoonKnight