Use Reflection to only get specific methods inside a DLL

-1

I'm trying to use reflection to get specific methods in a DLL so I can execute them but am getting an error:

Could not load file or assembly 'MyDLL.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

Not sure what I need to do to fix it. Can someone help with this?

Task.Factory.StartNew((Action)delegate
{
    try
    {
        int count = 1;
        Assembly assembly = Assembly.LoadFrom("MyDLL.dll");

        foreach (Type type in assembly.GetTypes())
        {
            if (type.IsClass == true)
            {
                MethodInfo[] methodInfo = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

                foreach (MethodInfo mi in methodInfo)
                {
                    // MyTests is the class object in MyDLL.
                    var instance = Activator.CreateInstance(@"MyDLL.dll", "MyTests"); // Error here
                    TestResult test = (TestResult)mi.Invoke(instance, null);
                    SendTestResult(test, false);

                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(5);
                    count++;
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
});
c#
reflection
asked on Stack Overflow Oct 17, 2019 by Wannabe

1 Answer

0

Review the documentation for Activator.CreateInstance(string assemblyName, string typeName):

assemblyName can be either of the following:
1. The simple name of an assembly, without its path or file extension. For example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.
2. The full name of a signed assembly, which consists of its simple name, version, culture, and public key token; for example, "TypeExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=181869f2f7435b51".

You want the first argument to be "MyDLL".

Also you will need to call Unwrap on the returned ObjectHandle to use it with reflection that way. You are better off using the overload Activator.CreateInstance(Type type) since you already have the type.

answered on Stack Overflow Oct 17, 2019 by Mike Zboray

User contributions licensed under CC BY-SA 3.0