dimanche 9 avril 2017

Cannot retrieve TypeInfo(s) from assembly due to ReflectionTypeLoadException

I am trying to retrieve all defined types into a .NET assembly by using System.Reflection in C#. First I load the assembly:

var assembly = Assembly.LoadFrom("C:\...\myassembly.dll");

Then I try to get all the TypeInfo for the types in the assembly:

try {
    var types = assembly.DefinedTypes;
}
catch(ReflectionTypeLoadException ex)
{
    var errorMessage = new StringBuilder();
    errorMessage.AppendLine($"Error loading defined types in assembly {this.assembly.FullName}. Found {ex.LoaderExceptions.Length} errors:");

    foreach (var innerException in ex.LoaderExceptions)
    {
        errorMessage.AppendLine($"{innerException.GetType().Name} - {innerException.HResult}: {innerException.Message}");
    }

    throw new InvalidOperationException(errorMessage.ToString(), ex);
}

Fail

The failure I have is ReflectionTypeLoadException and I get in ex.LoaderExceptions a lot of exceptions like:

-2146233054: Could not load type 'MyType' from assembly 'myassembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method '.ctor' has no implementation (no RVA)

Regarding the reflection context

I have found this question which deals about this same problem, ont of the suggestions was to use:

var assembly = Assembly.ReflectionOnlyLoadFrom("C:\...\myassembly.dll");

It did not work.

My question

My question is simple: how can I get all the TypeInfo from the available types by ignoring errors on types that are not fully defined in the assembly or that lack implementation?

I know that ex.Types will give me a list of types I can use from the exception, but that would give me a System.Type not a System.Reflection.TypeInfo. I want the latter as it has more information about the types which I need. The question I linked does not deal with this problem!





Aucun commentaire:

Enregistrer un commentaire