PRB: “System.Reflection.TargetInvocationException” Error Message When You Call the MethodInfo.Invoke Method
Symptoms
When you call the MethodInfo.Invoke method, you may receive the following error message:
An unhandled exception of type ‘System.Reflection.TargetInvocationException’ occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an invocation.
You may also receive an additional error message that is similar to the following error message:
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. —> System.IO.FileLoadException: ‘ClassLibrary1′ is not a valid file.
File name: “ClassLibrary1″
at ClassLibrary2.Class1.GetString()
Resolution
You receive the System.Reflection.TargetInvocationException error because the common language runtime calls the MethodInfo.Invoke method by using reflection.
When you load an assembly by using the Assembly.LoadFrom method, the common language runtime places the loaded assembly in the LoadFrom context of your application. Any probes for the dependencies of the assembly first probe the current application directory. If this probe fails, the common language runtime then probes the LoadFrom context of your application.
You may load an assembly that has a simply-named dependency that has the same file name as a file in the current application directory. When you try to invoke a method in the loaded assembly by using the MethodInfo.Invoke method, and the invoked method uses the dependency, the common language runtime first probes the current directory path. When the common language runtime finds a file that has the same file name as the dependency, the probe stops. However, if this file does not have the same assembly identity as the dependency, the assembly bind fails, and the common language runtime generates a System.IO.FileLoadException error that is passed to the System.Reflection.TargetInvocationException error. Therefore, you may notice the behavior that is mentioned in the “Symptoms” section.
