jeudi 17 octobre 2019

Use Reflection to only get specific methods inside a DLL

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);
    }
});




Aucun commentaire:

Enregistrer un commentaire