-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);
    }
});
Wannabe
  • 596
  • 1
  • 8
  • 22
  • Try removing the `.dll` from the `MyDLL.dll` string. Technically, assemblies can be multiple files, so assembly names don't have a file suffix. (It's just that usually it's the case that the file matches the assembly name.) – Joe Sewell Oct 17 '19 at 20:01
  • Possible duplicate of [Exception from HRESULT: 0x80131047](https://stackoverflow.com/questions/12520212/exception-from-hresult-0x80131047) and try using `Assembly.LoadFile()`... – Trevor Oct 17 '19 at 20:02
  • Try to use full path to file, check modifier access for this class – Basil Kosovan Oct 17 '19 at 20:02

1 Answers1

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.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122